LocalMusic.ets 494 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243
  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.setShowPlayPage()
  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.setShowPlayPage()
  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.setShowPlayPage()
  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. .objectFit(ImageFit.Contain)
  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. .geometryTransition('cover', { follow: true }) // 绑定标识符
  5588. Column() {
  5589. Text(this.currentSong?.name)
  5590. .fontSize(16)
  5591. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5592. .maxLines(1)
  5593. .fontColor(Color.White)
  5594. .fontWeight(500);
  5595. Row() {
  5596. Text(this.currentSong?.artist)
  5597. .margin({ top: 2 })
  5598. .fontSize(13)
  5599. .textAlign(TextAlign.Start)
  5600. .maxLines(1)
  5601. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5602. .fontColor(Color.White)
  5603. }
  5604. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5605. }
  5606. .padding({left:8})
  5607. .geometryTransition('name', { follow: true }) // 绑定标识符
  5608. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  5609. .margin({ right: isLeft?22:10 })
  5610. .visibility(isLeft? Visibility.Visible:Visibility.None)
  5611. }
  5612. .padding({ right: 18 })
  5613. .layoutWeight(isLeft?1:0)
  5614. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5615. .onClick(() => {
  5616. this.showPlayerView()
  5617. })
  5618. }
  5619. setShowPlayPage(){
  5620. this.getUIContext()?.animateTo({
  5621. duration: 500,
  5622. curve: Curve.Friction
  5623. }, () => {
  5624. this.isShowPlay = !this.isShowPlay;
  5625. });
  5626. }
  5627. //打开播放页
  5628. showPlayerView() {
  5629. if (ArrayUtil.isNotEmpty(this.songList)) {
  5630. this.setShowPlayPage()
  5631. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  5632. this.initLyric(lyricPath);
  5633. this.startAutoHide();
  5634. } else {
  5635. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  5636. }
  5637. }
  5638. @Builder
  5639. playConRigth() {
  5640. Row() {
  5641. SymbolGlyph($r('sys.symbol.backward_end_fill'))
  5642. .fontSize(28)
  5643. .fontColor([this.themeColor])
  5644. .alignSelf(ItemAlign.Center)
  5645. .visibility(this.isShowPrecious? Visibility.Visible:Visibility.None)
  5646. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5647. .margin({ left: 8, right: 14 })
  5648. .displayPriority(2)
  5649. .onClick(() => {
  5650. if (ArrayUtil.isNotEmpty(this.songList)) {
  5651. this.playPrevious()
  5652. } else {
  5653. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5654. }
  5655. })
  5656. //播放进度条
  5657. Stack() {
  5658. Progress({
  5659. value: Math.floor(this.progressValue),
  5660. type: ProgressType.Ring,
  5661. })
  5662. .color(this.themeColor)// 进度条前景色为灰色
  5663. .height(38)
  5664. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5665. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  5666. .height(36)
  5667. .width(36)
  5668. .displayPriority(3)
  5669. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5670. .fillColor(this.themeColor)
  5671. .onClick(() => {
  5672. if (ArrayUtil.isNotEmpty(this.songList)) {
  5673. console.info('onecold playOrPause 4642')
  5674. this.playOrPause()
  5675. } else {
  5676. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5677. }
  5678. })
  5679. }
  5680. SymbolGlyph($r('sys.symbol.forward_end_fill'))
  5681. .fontSize(28)
  5682. .fontColor([this.themeColor])
  5683. .alignSelf(ItemAlign.Center)
  5684. .margin({
  5685. right: 14,
  5686. left: 14
  5687. })
  5688. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5689. .displayPriority(2)
  5690. .onClick(() => {
  5691. if (ArrayUtil.isNotEmpty(this.songList)) {
  5692. this.playNext()
  5693. } else {
  5694. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5695. }
  5696. })
  5697. Image($r('app.media.hm_playlist'))
  5698. .height(26)
  5699. .width(26)
  5700. .displayPriority(1)
  5701. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5702. .fillColor(this.themeColor)
  5703. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  5704. height: '95%',
  5705. dragBar: true,
  5706. showClose: true,
  5707. blurStyle: BlurStyle.Thin,
  5708. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5709. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  5710. title: {
  5711. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5712. + `(${this.songList.length}首)`
  5713. }
  5714. })
  5715. .onClick(() => {
  5716. if (ArrayUtil.isNotEmpty(this.songList)) {
  5717. this.isShowSheet = !this.isShowSheet;
  5718. this.isFrontWhite = false
  5719. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  5720. this.scrollIndex()
  5721. } else {
  5722. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5723. }
  5724. })
  5725. }
  5726. }
  5727. scrollIndex(){
  5728. try {
  5729. setTimeout(() => {
  5730. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  5731. if(this.curIndex>60){
  5732. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  5733. }else{
  5734. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5735. }
  5736. })
  5737. }, 123)
  5738. }catch (error) {
  5739. console.error(`onecold scrollIndex出错: ${error}`);
  5740. }
  5741. }
  5742. //播放列表布局
  5743. @Builder
  5744. PlayListSheet() {
  5745. Column() {
  5746. this.PlayList()
  5747. }
  5748. .width('100%')
  5749. .height('100%')
  5750. }
  5751. @State titleStr: string = ''
  5752. @State ablumStr: string = ''
  5753. @State artistStr: string = ''
  5754. @State lyricConStr: string = ''
  5755. @State currentEditItem: string = ''
  5756. @State yearStr: string = ''
  5757. @State trackStr: string = ''
  5758. @State genreStr: string = ''
  5759. @State imagePathStr: string = ''
  5760. @State albumArtistStr: string = ''
  5761. @State composerStr: string = ''
  5762. @State lyricistStr: string = ''
  5763. @State commentStr: string = ''
  5764. @State discStr: string = ''
  5765. doUpdateData() {
  5766. setTimeout(() => {
  5767. if (this.modeType === 0) {
  5768. this.deleteCache(this.currentPath)
  5769. this.getSortedFiles(this.currentPath)
  5770. }
  5771. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5772. workerInstance.postMessage({ code: 3, data: this.context });
  5773. workerInstance.postMessage({ code: 4, data: this.context });
  5774. }, 999)
  5775. }
  5776. //编辑信息
  5777. async doEdit(item: VideoItem) {
  5778. if (!item) {
  5779. return
  5780. }
  5781. if (StrUtil.isEmpty(this.titleStr)) {
  5782. ToastUtil.showToast('标题不能为空')
  5783. return
  5784. }
  5785. DialogHelper.showLoadingDialog()
  5786. await PermissionUtil.activatePermission(item.filePath)
  5787. let tempOutPath = ''
  5788. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  5789. if(!item.filePath.toLowerCase().includes(this.packName)){
  5790. tempOutPath = this.currentPath + '/' + item.fileName
  5791. }
  5792. console.info('onecold tempOutPath ='+tempOutPath)
  5793. //用户更改了封面,那就内嵌下封面
  5794. if(StrUtil.isNotEmpty(this.imagePathStr)){
  5795. const resultCover:boolean = await changeMusicCover(this.context,
  5796. item.filePath,this.imagePathStr,true,tempOutPath);
  5797. this.imagePathStr = ''
  5798. if(resultCover){
  5799. ToastUtil.showToast('内嵌封面成功')
  5800. }
  5801. }
  5802. const metadata:FFMpegTags = {
  5803. title: this.titleStr,
  5804. artist: this.artistStr,
  5805. album: this.ablumStr,
  5806. TYER:this.yearStr,
  5807. genre:this.genreStr,
  5808. track:this.trackStr,
  5809. album_artist:this.albumArtistStr,
  5810. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  5811. COMPOSER:this.composerStr,
  5812. lyricist:this.lyricistStr,
  5813. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  5814. comment:this.commentStr,
  5815. disc:this.discStr,
  5816. };
  5817. let newInput = item.filePath
  5818. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  5819. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  5820. newInput = tempOutPath
  5821. tempOutPath = ''
  5822. }
  5823. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  5824. const result:boolean = await repairAudioMetadata(
  5825. newInput,
  5826. this.lyricConStr,
  5827. metadata,
  5828. true,
  5829. tempOutPath
  5830. );
  5831. if (result) {
  5832. if(!item.filePath.includes(this.packName)){
  5833. //内嵌成功的歌路径如果不是包含包名,则要入库
  5834. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  5835. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5836. this.table.insert(newItem, (id: number) => {
  5837. //加入数据库
  5838. if(this.modeType==0){
  5839. this.deleteCache(this.currentPath)
  5840. this.getSortedFiles(this.currentPath)
  5841. }
  5842. });
  5843. }
  5844. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  5845. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  5846. (success: boolean, error?: string) => {
  5847. // this.isShowEdit = false
  5848. if (success) {
  5849. console.log(" onecold 编辑信息成功,数据库已同步");
  5850. ToastUtil.showToast('内嵌音乐标签成功')
  5851. this.isShowMoreView = false
  5852. this.name = this.titleStr
  5853. if (item.filePath == this.currentSong?.filePath) {
  5854. this.currentSong.name = this.titleStr
  5855. this.artist = this.artistStr
  5856. this.currentSong.artist = this.artistStr
  5857. this.currentSong.album = this.ablumStr
  5858. this.currentSong.year = this.yearStr
  5859. this.currentSong.genre = this.genreStr
  5860. this.currentSong.track = this.trackStr
  5861. this.currentSong.lyricContent = this.lyricConStr
  5862. this.initLyric(item.filePath)
  5863. this.currentSong.ALBUMARTIST = this.albumArtistStr
  5864. this.currentSong.COMPOSER = this.composerStr
  5865. this.currentSong.LYRICIST = this.lyricistStr
  5866. this.currentSong.COMMENT = this.commentStr
  5867. }
  5868. this.doUpdateData()
  5869. } else {
  5870. // ToastUtil.showToast('保存失败' + error?.toString())
  5871. console.error(" onecold 编辑信息数据库失败原因: " + error);
  5872. }
  5873. // 关闭进度条
  5874. DialogHelper.closeLoading();
  5875. });
  5876. console.log(' onecold 元数据标签更新成功,');
  5877. } else {
  5878. // 关闭进度条
  5879. DialogHelper.closeLoading();
  5880. ToastUtil.showToast('内嵌音乐标签失败')
  5881. console.log('onecold 内嵌音乐标签失败');
  5882. }
  5883. this.longItemFilePath = ''
  5884. this.tempLyricContent = ''
  5885. this.isShowEdit = false
  5886. }
  5887. updateLyricToDB() {
  5888. }
  5889. @Builder
  5890. editSheet(item: VideoItem) {
  5891. Scroll() {
  5892. Column() {
  5893. this.editDetail(item)
  5894. }
  5895. }
  5896. .width('100%')
  5897. .height('100%')
  5898. }
  5899. @Builder
  5900. editDetail(item: VideoItem) {
  5901. Column() {
  5902. if (item) {
  5903. Row() {
  5904. Stack() {
  5905. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  5906. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  5907. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  5908. item.pixelMapPath)
  5909. .fillColor(this.themeColor)
  5910. .height(88)
  5911. .width(88)
  5912. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5913. .borderRadius(12)
  5914. .clip(true)
  5915. .opacity(this.opacityItem)// 绑定透明度
  5916. .margin({ left: 25 })
  5917. }
  5918. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5919. .onClick(async () => {
  5920. const imagePath:string | undefined = await this.goSelectImage(item);
  5921. if (imagePath) {
  5922. //用户更改过图片
  5923. this.imagePathStr = imagePath
  5924. }
  5925. })
  5926. .width('28%')
  5927. Row() {
  5928. Column() {
  5929. Text(item.name)
  5930. .fontSize(17)
  5931. .maxLines(1)
  5932. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5933. .animation({
  5934. duration: 555,
  5935. curve: 'Linear',
  5936. })
  5937. .fontColor(this.themeColor)
  5938. .margin({ left: 8 })
  5939. Row() {
  5940. Text(item.artist)
  5941. .fontSize(14)
  5942. .maxLines(1)
  5943. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5944. .padding({ top: 8 })
  5945. .fontColor(this.themeColor)
  5946. .margin({ left: 8 })
  5947. }
  5948. }
  5949. .height('100%')
  5950. .width(100)
  5951. .layoutWeight(1)
  5952. .justifyContent(FlexAlign.Center)
  5953. .alignItems(HorizontalAlign.Start)
  5954. Column() {
  5955. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5956. Row(){
  5957. SymbolGlyph($r('sys.symbol.picture'))
  5958. .fontSize(18)
  5959. .fontColor([Color.White])
  5960. Text('获取封面')
  5961. .margin({ left: 4 })
  5962. .fontSize(11)
  5963. .fontColor(Color.White)
  5964. .fontWeight(480)
  5965. .textAlign(TextAlign.Center)
  5966. }
  5967. .justifyContent(FlexAlign.Center)
  5968. }
  5969. .height(38)
  5970. .width(100)
  5971. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5972. .backgroundColor(this.themeColor)
  5973. .stateEffect(true)
  5974. .margin({ right: 35 })
  5975. .onClick(async () => {
  5976. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  5977. this.showTipsDialog();
  5978. return; // Return empty string when no API is configured
  5979. }
  5980. const imagePath:string | undefined = await this.doSearchCover(item);
  5981. console.info('onecold imagePath = '+imagePath)
  5982. if (StrUtil.isNotEmpty(imagePath)) {
  5983. //用户更改过图片
  5984. this.imagePathStr = imagePath
  5985. ToastUtil.showToast('获取封面成功')
  5986. }else{
  5987. ToastUtil.showToast('获取封面失败,请重试')
  5988. }
  5989. })
  5990. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5991. Row(){
  5992. SymbolGlyph($r('sys.symbol.input_mode'))
  5993. .fontSize(18)
  5994. .fontColor([Color.White])
  5995. Text('获取歌词')
  5996. .margin({ left: 4 })
  5997. .fontSize(11)
  5998. .fontColor(Color.White)
  5999. .fontWeight(480)
  6000. .textAlign(TextAlign.Center)
  6001. }
  6002. .justifyContent(FlexAlign.Center)
  6003. }
  6004. .height(38)
  6005. .width(100)
  6006. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6007. .backgroundColor(this.themeColor)
  6008. .stateEffect(true)
  6009. .margin({ top: 9, right: 35 })
  6010. .onClick(async () => {
  6011. //判断有没有设置api
  6012. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6013. if (StrUtil.isEmpty(apiUrl)) {
  6014. this.isLyricSetting = false
  6015. this.showTipsDialog()
  6016. return
  6017. }
  6018. let artist = item.artist
  6019. let title = item.name
  6020. if(!artist)
  6021. artist = ''
  6022. if(!title)
  6023. title = ''
  6024. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  6025. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6026. this.lyricConStr = res;
  6027. ToastUtil.showToast('获取歌词成功')
  6028. }else{
  6029. ToastUtil.showToast('获取歌词失败,请重试')
  6030. }
  6031. })
  6032. }
  6033. .justifyContent(FlexAlign.Start)
  6034. }
  6035. .height('100%')
  6036. .justifyContent(FlexAlign.Start)
  6037. .layoutWeight(1)
  6038. }
  6039. .width('100%')
  6040. .height(98)
  6041. Row() {
  6042. Text('标题:')
  6043. .fontSize(14)
  6044. .fontColor($r('app.color.text_color'))
  6045. .margin({ left: 22 })
  6046. TextInput({ text: item.name })
  6047. .height(40)
  6048. .maxLines(1)
  6049. .fontSize(14)
  6050. .layoutWeight(1)
  6051. .fontColor($r('app.color.text_color'))
  6052. .margin({ right: 20, left: 10 })
  6053. .onChange((val: string) => {
  6054. this.titleStr = val
  6055. })
  6056. }
  6057. .width('100%')
  6058. .margin({ top: 10, bottom: 10 })
  6059. .justifyContent(FlexAlign.Start)
  6060. Row() {
  6061. Text('艺术家:')
  6062. .fontSize(14)
  6063. .fontColor($r('app.color.text_color'))
  6064. .margin({ left: 22 })
  6065. TextInput({ text: item.artist })
  6066. .height(40)
  6067. .maxLines(1)
  6068. .fontSize(14)
  6069. .layoutWeight(1)
  6070. .fontColor($r('app.color.text_color'))
  6071. .margin({ right: 20, left: 10 })
  6072. .onChange((val: string) => {
  6073. this.artistStr = val
  6074. })
  6075. }
  6076. .width('100%')
  6077. .margin({ top: 10, bottom: 10 })
  6078. .justifyContent(FlexAlign.Start)
  6079. Row() {
  6080. Text('专辑名:')
  6081. .fontSize(14)
  6082. .fontColor($r('app.color.text_color'))
  6083. .margin({ left: 22 })
  6084. TextInput({ text: item.album })
  6085. .height(40)
  6086. .maxLines(1)
  6087. .fontSize(14)
  6088. .layoutWeight(1)
  6089. .fontColor($r('app.color.text_color'))
  6090. .margin({ right: 20, left: 10 })
  6091. .onChange((val: string) => {
  6092. this.ablumStr = val
  6093. })
  6094. }
  6095. .width('100%')
  6096. .margin({ top: 10, bottom: 10 })
  6097. .justifyContent(FlexAlign.Start)
  6098. Row() {
  6099. Column(){
  6100. Column(){
  6101. Text('歌词:')
  6102. .fontSize(14)
  6103. .fontColor($r('app.color.text_color'))
  6104. .margin({ top:9,left: 22 })
  6105. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6106. SymbolGlyph($r('sys.symbol.trash_fill'))
  6107. .fontSize(25)
  6108. .alignSelf(ItemAlign.Center)
  6109. .margin({ left: 22,top:25})
  6110. }
  6111. .backgroundColor(Color.Transparent)
  6112. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6113. Visibility.None:Visibility.Visible)
  6114. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6115. .onClick(()=>{
  6116. this.lyricConStr = ''
  6117. this.lyricContent = ''
  6118. this.tempLyricContent = ''
  6119. })
  6120. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6121. SymbolGlyph($r('sys.symbol.plus'))
  6122. .fontSize(25)
  6123. .alignSelf(ItemAlign.Center)
  6124. .margin({ left: 22,top:25})
  6125. }
  6126. .backgroundColor(Color.Transparent)
  6127. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6128. .onClick( ()=>{
  6129. this.callFilePickerSelectFileForLyric()
  6130. })
  6131. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6132. SymbolGlyph($r('sys.symbol.traditional_square'))
  6133. .fontSize(25)
  6134. .alignSelf(ItemAlign.Center)
  6135. .margin({ left: 22,top:25})
  6136. }
  6137. .backgroundColor(Color.Transparent)
  6138. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6139. Visibility.None:Visibility.Visible)
  6140. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6141. .onClick( ()=>{
  6142. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6143. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  6144. })
  6145. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6146. Image($r('app.media.jianti'))
  6147. .height(25)
  6148. .fillColor($r('app.color.text_color'))
  6149. .alignSelf(ItemAlign.Center)
  6150. .margin({ left: 22,top:25})
  6151. }
  6152. .backgroundColor(Color.Transparent)
  6153. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6154. Visibility.None:Visibility.Visible)
  6155. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6156. .onClick( ()=>{
  6157. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6158. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  6159. })
  6160. }
  6161. .layoutWeight(1)
  6162. }
  6163. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  6164. this.tempLyricContent })
  6165. .type(TextAreaType.NORMAL)
  6166. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  6167. .fontSize(14)
  6168. .layoutWeight(1)
  6169. .fontColor($r('app.color.text_color'))
  6170. .margin({ right: 20, left: 10 })
  6171. .onChange((val: string) => {
  6172. this.lyricConStr = val
  6173. })
  6174. }
  6175. .width('100%')
  6176. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  6177. .margin({ top: 10, bottom: 10 })
  6178. .justifyContent(FlexAlign.Start)
  6179. Row() {
  6180. Text('年份:')
  6181. .fontSize(14)
  6182. .fontColor($r('app.color.text_color'))
  6183. .margin({ left: 22 })
  6184. TextInput({ text: item.year })
  6185. .height(40)
  6186. .maxLines(1)
  6187. .fontSize(14)
  6188. .type(InputType.Number)
  6189. .layoutWeight(1)
  6190. .fontColor($r('app.color.text_color'))
  6191. .margin({ right: 20, left: 10 })
  6192. .onChange((val: string) => {
  6193. this.yearStr = val
  6194. })
  6195. }
  6196. .width('100%')
  6197. .margin({ top: 10, bottom: 10 })
  6198. .justifyContent(FlexAlign.Start)
  6199. Row() {
  6200. Text('音轨号:')
  6201. .fontSize(14)
  6202. .fontColor($r('app.color.text_color'))
  6203. .margin({ left: 22 })
  6204. TextInput({ text:item.track=='未知'?'': item.track })
  6205. .height(40)
  6206. .maxLines(1)
  6207. .fontSize(14)
  6208. .type(InputType.Number)
  6209. .layoutWeight(1)
  6210. .fontColor($r('app.color.text_color'))
  6211. .margin({ right: 20, left: 10 })
  6212. .onChange((val: string) => {
  6213. this.trackStr = val
  6214. })
  6215. }
  6216. .width('100%')
  6217. .margin({ top: 10, bottom: 10 })
  6218. .justifyContent(FlexAlign.Start)
  6219. Row() {
  6220. Text('碟号:')
  6221. .fontSize(14)
  6222. .fontColor($r('app.color.text_color'))
  6223. .margin({ left: 22 })
  6224. TextInput({ text:item.disc })
  6225. .height(40)
  6226. .maxLines(1)
  6227. .fontSize(14)
  6228. .type(InputType.Number)
  6229. .layoutWeight(1)
  6230. .fontColor($r('app.color.text_color'))
  6231. .margin({ right: 20, left: 10 })
  6232. .onChange((val: string) => {
  6233. this.discStr = val
  6234. })
  6235. }
  6236. .width('100%')
  6237. .margin({ top: 10, bottom: 10 })
  6238. .justifyContent(FlexAlign.Start)
  6239. Row() {
  6240. Text('风格:')
  6241. .fontSize(14)
  6242. .fontColor($r('app.color.text_color'))
  6243. .margin({ left: 22 })
  6244. TextInput({ text: item.genre })
  6245. .height(40)
  6246. .maxLines(1)
  6247. .fontSize(14)
  6248. .layoutWeight(1)
  6249. .fontColor($r('app.color.text_color'))
  6250. .margin({ right: 20, left: 10 })
  6251. .onChange((val: string) => {
  6252. this.genreStr = val
  6253. })
  6254. }
  6255. .width('100%')
  6256. .margin({ top: 10, bottom: 10 })
  6257. .justifyContent(FlexAlign.Start)
  6258. Row() {
  6259. Text('专辑艺术家:')
  6260. .fontSize(14)
  6261. .fontColor($r('app.color.text_color'))
  6262. .margin({ left: 22 })
  6263. TextInput({ text: item.ALBUMARTIST })
  6264. .height(40)
  6265. .maxLines(1)
  6266. .fontSize(14)
  6267. .layoutWeight(1)
  6268. .fontColor($r('app.color.text_color'))
  6269. .margin({ right: 20, left: 10 })
  6270. .onChange((val: string) => {
  6271. this.albumArtistStr = val
  6272. })
  6273. }
  6274. .width('100%')
  6275. .margin({ top: 10, bottom: 10 })
  6276. .justifyContent(FlexAlign.Start)
  6277. Row() {
  6278. Text('作曲:')
  6279. .fontSize(14)
  6280. .fontColor($r('app.color.text_color'))
  6281. .margin({ left: 22 })
  6282. TextInput({ text: item.COMPOSER })
  6283. .height(40)
  6284. .maxLines(1)
  6285. .fontSize(14)
  6286. .layoutWeight(1)
  6287. .fontColor($r('app.color.text_color'))
  6288. .margin({ right: 20, left: 10 })
  6289. .onChange((val: string) => {
  6290. this.composerStr = val
  6291. })
  6292. }
  6293. .width('100%')
  6294. .margin({ top: 10, bottom: 10 })
  6295. .justifyContent(FlexAlign.Start)
  6296. Row() {
  6297. Text('作词:')
  6298. .fontSize(14)
  6299. .fontColor($r('app.color.text_color'))
  6300. .margin({ left: 22 })
  6301. TextInput({ text: item.LYRICIST })
  6302. .height(40)
  6303. .maxLines(1)
  6304. .fontSize(14)
  6305. .layoutWeight(1)
  6306. .fontColor($r('app.color.text_color'))
  6307. .margin({ right: 20, left: 10 })
  6308. .onChange((val: string) => {
  6309. this.lyricistStr = val
  6310. })
  6311. }
  6312. .width('100%')
  6313. .margin({ top: 10, bottom: 10 })
  6314. .justifyContent(FlexAlign.Start)
  6315. Row() {
  6316. Text('注释:')
  6317. .fontSize(14)
  6318. .fontColor($r('app.color.text_color'))
  6319. .margin({ left: 22 })
  6320. TextInput({ text: item.COMMENT })
  6321. .height(40)
  6322. .maxLines(1)
  6323. .fontSize(14)
  6324. .layoutWeight(1)
  6325. .fontColor($r('app.color.text_color'))
  6326. .margin({ right: 20, left: 10 })
  6327. .onChange((val: string) => {
  6328. this.commentStr = val
  6329. })
  6330. }
  6331. .width('100%')
  6332. .margin({ top: 10, bottom: 10 })
  6333. .justifyContent(FlexAlign.Start)
  6334. Row() {
  6335. Button('保存')
  6336. .fontColor(Color.White)
  6337. .layoutWeight(1)
  6338. .height(50)
  6339. .width(100)
  6340. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6341. .backgroundColor(this.themeColor)
  6342. .stateEffect(true)
  6343. .margin({ right: 20, bottom: 20 })
  6344. .onClick(async () => {
  6345. this.doEdit(item)
  6346. })
  6347. Button('取消')
  6348. .fontColor(Color.White)
  6349. .layoutWeight(1)
  6350. .height(50)
  6351. .width(100)
  6352. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6353. .backgroundColor(this.themeColor)
  6354. .stateEffect(true)
  6355. .margin({ left: 20, bottom: 20 })
  6356. .onClick(async () => {
  6357. if(this.isGridMusic){
  6358. this.longItemFilePath =''
  6359. }else{
  6360. this.isShowEdit = false
  6361. }
  6362. this.setEditStrEmpty()
  6363. if(this.isShowPlay){
  6364. this.isShowEdit = false
  6365. }
  6366. })
  6367. }
  6368. .margin({
  6369. left: 38,
  6370. right: 38,
  6371. top: 10,
  6372. bottom: 10
  6373. })
  6374. .width(250)
  6375. .height(60)
  6376. }
  6377. }
  6378. .margin({ bottom: 20 })
  6379. }
  6380. setEditStrEmpty(){
  6381. this.imagePathStr = ''
  6382. this.lyricConStr = ''
  6383. this.artistStr = ''
  6384. this.titleStr = ''
  6385. this.ablumStr = ''
  6386. this.genreStr = ''
  6387. this.yearStr = ''
  6388. this.trackStr = ''
  6389. this.albumArtistStr = ''
  6390. this.composerStr = ''
  6391. this.lyricistStr = ''
  6392. this.commentStr = ''
  6393. this.discStr = ''
  6394. }
  6395. @Builder
  6396. detailSheet(item:VideoItem) {
  6397. Scroll() {
  6398. Column() {
  6399. this.songDetail(item)
  6400. }
  6401. }
  6402. .width('100%')
  6403. .height('100%')
  6404. }
  6405. @Builder
  6406. songDetail(currentItem:VideoItem) {
  6407. Column() {
  6408. if (currentItem) {
  6409. Row() {
  6410. Stack() {
  6411. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  6412. currentItem.pixelMapPath)
  6413. .fillColor(this.themeColor)
  6414. .height(80)
  6415. .width(80)
  6416. .borderRadius(10)
  6417. .opacity(this.opacityItem)// 绑定透明度
  6418. .margin({ left: 22 })
  6419. }
  6420. Column() {
  6421. Column() {
  6422. Text(currentItem.name)
  6423. .fontSize(16)
  6424. .maxLines(1)
  6425. .animation({
  6426. duration: 555,
  6427. curve: 'Linear',
  6428. })
  6429. .fontColor($r('app.color.text_color'))
  6430. .margin({ left: 15 })
  6431. }
  6432. .height('100%')
  6433. .width('100%')
  6434. .justifyContent(FlexAlign.Center)
  6435. .alignItems(HorizontalAlign.Start)
  6436. }
  6437. .height('100%')
  6438. }
  6439. .width('100%')
  6440. .height(90)
  6441. .justifyContent(FlexAlign.SpaceBetween)
  6442. Row() {
  6443. Text('艺术家:')
  6444. .fontSize(14)
  6445. .fontColor($r('app.color.text_color'))
  6446. .margin({ left: 22 })
  6447. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  6448. .fontSize(14)
  6449. .fontColor($r('app.color.text_color'))
  6450. .margin({ left: 10 })
  6451. .layoutWeight(1)
  6452. }
  6453. .width('100%')
  6454. .margin({ top: 10, bottom: 10 })
  6455. .justifyContent(FlexAlign.Start)
  6456. Row() {
  6457. Text('专辑名:')
  6458. .fontSize(14)
  6459. .fontColor($r('app.color.text_color'))
  6460. .margin({ left: 22 })
  6461. Text(currentItem?.album ?currentItem.album : '未知专辑')
  6462. .fontSize(14)
  6463. .margin({ left: 10 })
  6464. .fontColor($r('app.color.text_color'))
  6465. .layoutWeight(1)
  6466. }
  6467. .width('100%')
  6468. .margin({ top: 10, bottom: 10 })
  6469. .justifyContent(FlexAlign.Start)
  6470. Row() {
  6471. Text('时长:')
  6472. .fontSize(14)
  6473. .fontColor($r('app.color.text_color'))
  6474. .margin({ left: 22 })
  6475. Text(StrUtil.isEmpty(currentItem.duration)?
  6476. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  6477. .fontSize(14)
  6478. .margin({ left: 10 })
  6479. .fontColor($r('app.color.text_color'))
  6480. .layoutWeight(1)
  6481. }
  6482. .width('100%')
  6483. .margin({ top: 10, bottom: 10 })
  6484. .justifyContent(FlexAlign.Start)
  6485. Row() {
  6486. Text('采样率:')
  6487. .fontSize(14)
  6488. .fontColor($r('app.color.text_color'))
  6489. .margin({ left: 22 })
  6490. Text(Utility.convertToKHz(currentItem.sampleRate))
  6491. .fontSize(14)
  6492. .margin({ left: 10 })
  6493. .fontColor($r('app.color.text_color'))
  6494. .layoutWeight(1)
  6495. }
  6496. .width('100%')
  6497. .margin({ top: 10, bottom: 10 })
  6498. .justifyContent(FlexAlign.Start)
  6499. Row() {
  6500. Text('比特率:')
  6501. .fontSize(14)
  6502. .fontColor($r('app.color.text_color'))
  6503. .margin({ left: 22 })
  6504. Text(currentItem.bit_rate)
  6505. .fontSize(14)
  6506. .margin({ left: 10 })
  6507. .fontColor($r('app.color.text_color'))
  6508. .layoutWeight(1)
  6509. }
  6510. .width('100%')
  6511. .margin({ top: 10, bottom: 10 })
  6512. .justifyContent(FlexAlign.Start)
  6513. Row() {
  6514. Text('位深:')
  6515. .fontSize(14)
  6516. .fontColor($r('app.color.text_color'))
  6517. .margin({ left: 22 })
  6518. Text(`${currentItem.bits_per_raw_sample} bits`)
  6519. .fontSize(14)
  6520. .margin({ left: 10 })
  6521. .fontColor($r('app.color.text_color'))
  6522. .layoutWeight(1)
  6523. }
  6524. .width('100%')
  6525. .margin({ top: 10, bottom: 10 })
  6526. .justifyContent(FlexAlign.Start)
  6527. Row() {
  6528. Text('声道:')
  6529. .fontSize(14)
  6530. .fontColor($r('app.color.text_color'))
  6531. .margin({ left: 22 })
  6532. Text(`${currentItem.channels}`)
  6533. .fontSize(14)
  6534. .margin({ left: 10 })
  6535. .fontColor($r('app.color.text_color'))
  6536. .layoutWeight(1)
  6537. }
  6538. .width('100%')
  6539. .margin({ top: 10, bottom: 10 })
  6540. .justifyContent(FlexAlign.Start)
  6541. Row() {
  6542. Text('声道布局:')
  6543. .fontSize(14)
  6544. .fontColor($r('app.color.text_color'))
  6545. .margin({ left: 22 })
  6546. Text(`${currentItem.channel_layout}`)
  6547. .fontSize(14)
  6548. .margin({ left: 10 })
  6549. .fontColor($r('app.color.text_color'))
  6550. .layoutWeight(1)
  6551. }
  6552. .width('100%')
  6553. .margin({ top: 10, bottom: 10 })
  6554. .justifyContent(FlexAlign.Start)
  6555. Row() {
  6556. Text('起始播放点:')
  6557. .fontSize(14)
  6558. .fontColor($r('app.color.text_color'))
  6559. .margin({ left: 22 })
  6560. Text(`${currentItem.start_time}`)
  6561. .fontSize(14)
  6562. .margin({ left: 10 })
  6563. .fontColor($r('app.color.text_color'))
  6564. .layoutWeight(1)
  6565. }
  6566. .width('100%')
  6567. .margin({ top: 10, bottom: 10 })
  6568. .justifyContent(FlexAlign.Start)
  6569. Row() {
  6570. Text('风格:')
  6571. .fontSize(14)
  6572. .fontColor($r('app.color.text_color'))
  6573. .margin({ left: 22 })
  6574. Text(currentItem.genre)
  6575. .fontSize(14)
  6576. .margin({ left: 10 })
  6577. .fontColor($r('app.color.text_color'))
  6578. .layoutWeight(1)
  6579. }
  6580. .width('100%')
  6581. .margin({ top: 10, bottom: 10 })
  6582. .justifyContent(FlexAlign.Start)
  6583. Row() {
  6584. Text('发行时间:')
  6585. .fontSize(14)
  6586. .fontColor($r('app.color.text_color'))
  6587. .margin({ left: 22 })
  6588. Text(currentItem.year)
  6589. .fontSize(14)
  6590. .margin({ left: 10 })
  6591. .fontColor($r('app.color.text_color'))
  6592. .layoutWeight(1)
  6593. }
  6594. .width('100%')
  6595. .margin({ top: 10, bottom: 10 })
  6596. .justifyContent(FlexAlign.Start)
  6597. Row() {
  6598. Text('质量评分:')
  6599. .fontSize(14)
  6600. .fontColor($r('app.color.text_color'))
  6601. .margin({ left: 22 })
  6602. Text(currentItem.probe_score+"")
  6603. .fontSize(14)
  6604. .margin({ left: 10 })
  6605. .fontColor($r('app.color.text_color'))
  6606. .layoutWeight(1)
  6607. }
  6608. .width('100%')
  6609. .margin({ top: 10, bottom: 10 })
  6610. .justifyContent(FlexAlign.Start)
  6611. Row() {
  6612. Text('音轨号:')
  6613. .fontSize(14)
  6614. .fontColor($r('app.color.text_color'))
  6615. .margin({ left: 22 })
  6616. Text(currentItem.track)
  6617. .fontSize(14)
  6618. .margin({ left: 10 })
  6619. .fontColor($r('app.color.text_color'))
  6620. .layoutWeight(1)
  6621. }
  6622. .width('100%')
  6623. .margin({ top: 10, bottom: 10 })
  6624. .justifyContent(FlexAlign.Start)
  6625. Row() {
  6626. Text('碟号:')
  6627. .fontSize(14)
  6628. .fontColor($r('app.color.text_color'))
  6629. .margin({ left: 22 })
  6630. Text(currentItem.disc)
  6631. .fontSize(14)
  6632. .margin({ left: 10 })
  6633. .fontColor($r('app.color.text_color'))
  6634. .layoutWeight(1)
  6635. }
  6636. .width('100%')
  6637. .margin({ top: 10, bottom: 10 })
  6638. .justifyContent(FlexAlign.Start)
  6639. Row() {
  6640. Text('专辑艺术家:')
  6641. .fontSize(14)
  6642. .fontColor($r('app.color.text_color'))
  6643. .margin({ left: 22 })
  6644. Text(currentItem.ALBUMARTIST)
  6645. .fontSize(14)
  6646. .margin({ left: 10 })
  6647. .fontColor($r('app.color.text_color'))
  6648. .layoutWeight(1)
  6649. }
  6650. .width('100%')
  6651. .margin({ top: 10, bottom: 10 })
  6652. .justifyContent(FlexAlign.Start)
  6653. Row() {
  6654. Text('作曲家:')
  6655. .fontSize(14)
  6656. .fontColor($r('app.color.text_color'))
  6657. .margin({ left: 22 })
  6658. Text(currentItem.COMPOSER)
  6659. .fontSize(14)
  6660. .margin({ left: 10 })
  6661. .fontColor($r('app.color.text_color'))
  6662. .layoutWeight(1)
  6663. }
  6664. .width('100%')
  6665. .margin({ top: 10, bottom: 10 })
  6666. .justifyContent(FlexAlign.Start)
  6667. Row() {
  6668. Text('作词家:')
  6669. .fontSize(14)
  6670. .fontColor($r('app.color.text_color'))
  6671. .margin({ left: 22 })
  6672. Text(currentItem.LYRICIST)
  6673. .fontSize(14)
  6674. .margin({ left: 10 })
  6675. .fontColor($r('app.color.text_color'))
  6676. .layoutWeight(1)
  6677. }
  6678. .width('100%')
  6679. .margin({ top: 10, bottom: 10 })
  6680. .justifyContent(FlexAlign.Start)
  6681. Row() {
  6682. Text('注释:')
  6683. .fontSize(14)
  6684. .fontColor($r('app.color.text_color'))
  6685. .margin({ left: 22 })
  6686. Text(currentItem.COMMENT)
  6687. .fontSize(14)
  6688. .margin({ left: 10 })
  6689. .fontColor($r('app.color.text_color'))
  6690. .layoutWeight(1)
  6691. }
  6692. .width('100%')
  6693. .margin({ top: 10, bottom: 10 })
  6694. .justifyContent(FlexAlign.Start)
  6695. Row() {
  6696. Text('格式:')
  6697. .fontSize(14)
  6698. .fontColor($r('app.color.text_color'))
  6699. .margin({ left: 22 })
  6700. Text(Utility.formatMimeType(currentItem.mimeType))
  6701. .fontSize(14)
  6702. .margin({ left: 10 })
  6703. .fontColor($r('app.color.text_color'))
  6704. .layoutWeight(1)
  6705. }
  6706. .width('100%')
  6707. .margin({ top: 10, bottom: 10 })
  6708. .justifyContent(FlexAlign.Start)
  6709. Row() {
  6710. Text('播放次数:')
  6711. .fontSize(14)
  6712. .fontColor($r('app.color.text_color'))
  6713. .margin({ left: 22 })
  6714. Text(currentItem.playCount?.toString())
  6715. .fontSize(14)
  6716. .margin({ left: 10 })
  6717. .fontColor($r('app.color.text_color'))
  6718. .layoutWeight(1)
  6719. }
  6720. .width('100%')
  6721. .margin({ top: 10, bottom: 10 })
  6722. .justifyContent(FlexAlign.Start)
  6723. Row() {
  6724. Text('流数量:')
  6725. .fontSize(14)
  6726. .fontColor($r('app.color.text_color'))
  6727. .margin({ left: 22 })
  6728. Text(currentItem.nb_streams?.toString())
  6729. .fontSize(14)
  6730. .margin({ left: 10 })
  6731. .fontColor($r('app.color.text_color'))
  6732. .layoutWeight(1)
  6733. }
  6734. .width('100%')
  6735. .margin({ top: 10, bottom: 10 })
  6736. .justifyContent(FlexAlign.Start)
  6737. Row() {
  6738. Text('文件大小:')
  6739. .fontSize(14)
  6740. .fontColor($r('app.color.text_color'))
  6741. .margin({ left: 22 })
  6742. Text(currentItem.size)
  6743. .fontSize(14)
  6744. .margin({ left: 10 })
  6745. .fontColor($r('app.color.text_color'))
  6746. .layoutWeight(1)
  6747. }
  6748. .width('100%')
  6749. .margin({ top: 10, bottom: 10 })
  6750. .justifyContent(FlexAlign.Start)
  6751. Row() {
  6752. Text('文件名:')
  6753. .fontSize(14)
  6754. .fontColor($r('app.color.text_color'))
  6755. .margin({ left: 22 })
  6756. Text(currentItem.fileName)
  6757. .fontSize(14)
  6758. .margin({ left: 10 })
  6759. .fontColor($r('app.color.text_color'))
  6760. .layoutWeight(1)
  6761. }
  6762. .width('100%')
  6763. .margin({ top: 10, bottom: 10 })
  6764. .justifyContent(FlexAlign.Start)
  6765. Row() {
  6766. Text('修改时间:')
  6767. .fontSize(14)
  6768. .fontColor($r('app.color.text_color'))
  6769. .margin({ left: 22 })
  6770. Text(currentItem.cTime)
  6771. .fontSize(14)
  6772. .margin({ left: 10 })
  6773. .fontColor($r('app.color.text_color'))
  6774. .layoutWeight(1)
  6775. }
  6776. .width('100%')
  6777. .margin({ top: 10, bottom: 10 })
  6778. .justifyContent(FlexAlign.Start)
  6779. Row() {
  6780. Text('存放目录:')
  6781. .fontSize(14)
  6782. .fontColor($r('app.color.text_color'))
  6783. .margin({ left: 22 })
  6784. Text(currentItem.filePath)
  6785. .fontSize(12)
  6786. .margin({ left: 10 })
  6787. .fontColor($r('app.color.text_color'))
  6788. .layoutWeight(1)
  6789. }
  6790. .margin({ top: 10, bottom: 10 })
  6791. .width('100%')
  6792. .justifyContent(FlexAlign.Start)
  6793. Row() {
  6794. Text('内嵌歌词:')
  6795. .fontSize(14)
  6796. .fontColor($r('app.color.text_color'))
  6797. .margin({ left: 22 })
  6798. Text(currentItem.lyricContent)
  6799. .fontSize(12)
  6800. .copyOption(CopyOptions.InApp)
  6801. .margin({ left: 10 })
  6802. .fontColor($r('app.color.text_color'))
  6803. .layoutWeight(1)
  6804. }
  6805. .margin({ top: 10, bottom: 10 })
  6806. .width('100%')
  6807. .justifyContent(FlexAlign.Start)
  6808. }
  6809. }
  6810. .margin({ bottom: 20 })
  6811. }
  6812. //定时关闭布局
  6813. @Builder
  6814. TimeCloseSheet() {
  6815. Scroll() {
  6816. Column() {
  6817. this.TimeClose()
  6818. }
  6819. }
  6820. .width('100%')
  6821. .height('100%')
  6822. }
  6823. //倒计时关闭音乐,退出App功能实现。
  6824. @State selectedMinutes: number = 0 // 0表示未开启
  6825. @State remainingSeconds: number = 0
  6826. // 预设时间选项
  6827. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  6828. private formatTime(seconds: number): string {
  6829. const mins = Math.floor(seconds / 60)
  6830. const secs = seconds % 60
  6831. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  6832. }
  6833. // 开始倒计时
  6834. private handleTimeSelect(minutes: number) {
  6835. if (minutes === this.selectedMinutes) {
  6836. this.stopCountdown();
  6837. this.selectedMinutes = 0;
  6838. return;
  6839. }
  6840. this.selectedMinutes = minutes;
  6841. this.remainingSeconds = minutes * 60;
  6842. this.startCountdown(); // 新增调用
  6843. }
  6844. @Builder
  6845. TimeClose() {
  6846. Column() {
  6847. // 倒计时显示区域
  6848. Text(this.selectedMinutes > 0 ?
  6849. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  6850. "定时关闭未开启")
  6851. .fontSize(17)
  6852. .fontColor($r('app.color.text_color'))
  6853. .margin({ top: 2, bottom: 8 });
  6854. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6855. ForEach(this.presetTimes, (minutes: number, index: number) => {
  6856. // 单行时间选项容器
  6857. Row() {
  6858. // 文字描述区域
  6859. Text(this.getDisplayText(minutes))
  6860. .fontSize(15)
  6861. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  6862. $r('app.color.text_color'))// 选中态颜色变化
  6863. .textAlign(TextAlign.Start)
  6864. .layoutWeight(1); // 占据剩余空间
  6865. // 复选框样式的选择器
  6866. Row() {
  6867. if (minutes === this.selectedMinutes) {
  6868. // 选中状态 - 带勾号的圆形复选框
  6869. Row() {
  6870. // 使用系统内置的勾号图标
  6871. Image($r('sys.media.ohos_ic_public_ok'))
  6872. .width(14)
  6873. .height(14)
  6874. .fillColor(Color.White)
  6875. }
  6876. .width(24)
  6877. .height(24)
  6878. .borderRadius(12)
  6879. .backgroundColor(this.themeColor)
  6880. .justifyContent(FlexAlign.Center)
  6881. .alignItems(VerticalAlign.Center)
  6882. } else {
  6883. // 未选中状态的圆形边框
  6884. Row()
  6885. .width(24)
  6886. .height(24)
  6887. .borderRadius(12)
  6888. .border({
  6889. width: 2,
  6890. color: $r('app.color.text_color'),
  6891. style: BorderStyle.Solid
  6892. })
  6893. .backgroundColor(Color.Transparent)
  6894. }
  6895. }
  6896. .width(24)
  6897. .height(24)
  6898. .margin({ left: 20 })
  6899. .justifyContent(FlexAlign.Center)
  6900. .alignItems(VerticalAlign.Center)
  6901. }
  6902. .width('100%')
  6903. .padding({
  6904. top: 18,
  6905. bottom: 18,
  6906. left: 18,
  6907. right: 18
  6908. })
  6909. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  6910. $r('app.color.bottom_control_background')) // 选中背景高亮
  6911. .borderRadius(12)
  6912. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6913. .margin({ bottom: 18 })
  6914. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  6915. });
  6916. }
  6917. .width('100%')
  6918. .padding(16)
  6919. }
  6920. }
  6921. // 获取显示文本
  6922. private getDisplayText(minutes: number): string {
  6923. if (minutes === -1) {
  6924. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  6925. }
  6926. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  6927. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  6928. }
  6929. // 处理选择事件
  6930. private handleSelect(minutes: number): void {
  6931. if (minutes === -1) { // 自定义
  6932. // 弹出自定义时间对话框
  6933. DialogHelper.showTextInputDialog({
  6934. title: '自定义时间',
  6935. maskColor: Color.Transparent,
  6936. inputType: InputType.Number,
  6937. text: '',
  6938. onChange: (text) => {
  6939. console.error("onChange: " + text);
  6940. },
  6941. onAction: (action, dialogId, content) => {
  6942. if (action == DialogAction.TWO) {
  6943. const customMinutes = Number(content);
  6944. if (customMinutes > 0) {
  6945. this.handleTimeSelect(customMinutes); // 设置自定义时间
  6946. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  6947. }
  6948. }
  6949. }
  6950. });
  6951. } else {
  6952. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  6953. }
  6954. }
  6955. // 添加定时器引用
  6956. private timerId: number = -1;
  6957. // 启动/重置倒计时
  6958. private startCountdown() {
  6959. // 清除旧定时器
  6960. if (this.timerId !== -1) {
  6961. clearInterval(this.timerId);
  6962. }
  6963. // 创建新定时器
  6964. if (this.selectedMinutes > 0) {
  6965. this.timerId = setInterval(() => {
  6966. if (this.remainingSeconds === 15) {
  6967. this.showConfirmationDialog();
  6968. }
  6969. if (this.remainingSeconds > 0) {
  6970. this.remainingSeconds -= 1;
  6971. } else {
  6972. this.stopCountdown();
  6973. this.handleTimeout();
  6974. }
  6975. }, 1000);
  6976. }
  6977. }
  6978. // 15倒计时后再次提示显示确认是否关闭App对话框
  6979. private showConfirmationDialog() {
  6980. DialogHelper.showAlertDialog({
  6981. backgroundColor: $r('app.color.btn_green'),
  6982. title: '确认关闭',
  6983. maskColor: Color.Transparent,
  6984. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  6985. borderStyle: BorderStyle.Dashed,
  6986. primaryButton: '暂不关闭',
  6987. secondaryButton: '确定',
  6988. onAction: (action) => {
  6989. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  6990. this.stopCountdown();
  6991. this.selectedMinutes = 0
  6992. } else if (action == DialogAction.TWO) {
  6993. }
  6994. }
  6995. })
  6996. }
  6997. // 停止倒计时
  6998. private stopCountdown() {
  6999. if (this.timerId !== -1) {
  7000. clearInterval(this.timerId);
  7001. this.timerId = -1;
  7002. }
  7003. }
  7004. // 超时处理
  7005. private handleTimeout() {
  7006. // 执行播放器关闭逻辑
  7007. this.selectedMinutes = 0;
  7008. ToastUtil.showToast(" 定时关闭已完成");
  7009. this.stop(); // 假设存在的播放器实例
  7010. //退出APP
  7011. const mContext = getContext(this) as common.UIAbilityContext
  7012. mContext.terminateSelf();
  7013. AvSessionController.getInstance(true).unregisterSessionListener()
  7014. }
  7015. //倒计时关闭音乐,退出App功能实现结束。
  7016. //播放列表的拖动List 重新排序
  7017. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  7018. //左滑操作 移动文件 重命名 删除等操作
  7019. @Builder
  7020. sonButton(item: VideoItem, index: number, filePath: string) {
  7021. Row() {
  7022. //加入下一首播放
  7023. Button() {
  7024. Image($r('app.media.next_to_play'))
  7025. .fillColor(Color.White)
  7026. .width(20)
  7027. }
  7028. .width(40)
  7029. .height(40)
  7030. .type(ButtonType.Circle)
  7031. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7032. .backgroundColor(this.themeColor)
  7033. .margin(5)
  7034. .onClick(() => {
  7035. this.addToNextPlay(item);
  7036. })
  7037. Button() {
  7038. Image($r('app.media.close'))
  7039. .fillColor(Color.White)
  7040. .width(20)
  7041. }
  7042. .width(40)
  7043. .height(40)
  7044. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7045. .type(ButtonType.Circle)
  7046. .backgroundColor(this.themeColor)
  7047. .margin(5)
  7048. .onClick(() => {
  7049. this.songList.splice(Number(index), 1)
  7050. this.sonDataSource.pushArrayData(this.songList)
  7051. })
  7052. Button() {
  7053. Image($r('app.media.share2'))
  7054. .fillColor(Color.White)
  7055. .width(20)
  7056. }
  7057. .width(40)
  7058. .height(40)
  7059. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7060. .type(ButtonType.Circle)
  7061. .backgroundColor(this.themeColor)
  7062. .margin(5)
  7063. .onClick(() => {
  7064. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  7065. })
  7066. }
  7067. }
  7068. itemMoveSon(index: number, newIndex: number): void {
  7069. if (newIndex < 0 || newIndex >= this.songList.length) {
  7070. return;
  7071. }
  7072. let tmp = this.songList.splice(index, 1);
  7073. this.songList.splice(newIndex, 0, tmp[0]);
  7074. this.sonDataSource.pushArrayData(this.songList)
  7075. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  7076. if(this.modeType==4&&this.playlistTable){
  7077. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  7078. }
  7079. }
  7080. @Builder
  7081. PlayList() {
  7082. List({ scroller: this.playListScroller }) {
  7083. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  7084. ListItem() {
  7085. this.MusicItemSon(item, index)
  7086. }
  7087. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  7088. .animation({
  7089. duration: 666,
  7090. curve: 'ease-in-out' // 可选动画曲线
  7091. })
  7092. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  7093. TransitionEffect.scale({ x: 0, y: 0 })))
  7094. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  7095. //拖动List关键代码开始
  7096. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  7097. .zIndex(this.dragItem === index ? 1 : 0)
  7098. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  7099. .gesture(
  7100. GestureGroup(GestureMode.Sequence,
  7101. LongPressGesture({ repeat: true })
  7102. .onAction((event?: GestureEvent) => {
  7103. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7104. this.scaleItem = index
  7105. })
  7106. })
  7107. .onActionEnd(() => {
  7108. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7109. this.scaleItem = -1
  7110. })
  7111. }),
  7112. PanGesture({ fingers: 1, direction: null, distance: 0 })
  7113. .onActionStart(() => {
  7114. this.dragItem = index // 记录当前拖动项索引
  7115. this.dragRefOffset = 0 // 重置偏移基准
  7116. })
  7117. .onActionUpdate((event: GestureEvent) => {
  7118. this.offsetY = event.offsetY - this.dragRefOffset;
  7119. this.neighborItem = -1;
  7120. let indexA = this.songList.indexOf(item);
  7121. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  7122. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  7123. let value: number = 0;
  7124. if (this.offsetY < 0) {
  7125. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  7126. this.neighborItem = indexA - 1;
  7127. this.neighborScale = 1 - value / 20;
  7128. } else if (this.offsetY > 0) {
  7129. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  7130. this.neighborItem = indexA + 1;
  7131. this.neighborScale = 1 - value / 20;
  7132. }
  7133. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  7134. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7135. this.offsetY -= this.ITEM_INTV;
  7136. this.dragRefOffset += this.ITEM_INTV;
  7137. this.itemMoveSon(indexA, indexA + 1);
  7138. });
  7139. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  7140. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7141. this.offsetY += this.ITEM_INTV;
  7142. this.dragRefOffset -= this.ITEM_INTV;
  7143. this.itemMoveSon(indexA, indexA - 1);
  7144. });
  7145. }
  7146. })
  7147. .onActionEnd((event: GestureEvent) => {
  7148. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7149. this.dragItem = -1
  7150. this.neighborItem = -1
  7151. })
  7152. animateTo({
  7153. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7154. }, () => {
  7155. this.scaleItem = -1
  7156. })
  7157. })
  7158. )
  7159. .onCancel(() => {
  7160. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7161. this.dragItem = -1
  7162. this.neighborItem = -1
  7163. })
  7164. animateTo({
  7165. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7166. }, () => {
  7167. this.scaleItem = -1
  7168. })
  7169. })
  7170. ) //拖动List关键代码结束
  7171. .onClick(() => {
  7172. this.doPlay(item, index, true)
  7173. })
  7174. }, (item: VideoItem) => item.filePath)
  7175. }
  7176. .width('100%')
  7177. .height('100%')
  7178. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7179. // .animation({ duration: 500, curve: Curve.Ease }))
  7180. .cachedCount(10)
  7181. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7182. .gesture(PinchGesture({ fingers: 2 })
  7183. .onActionEnd((event: GestureEvent) => {
  7184. this.setSonListTwoFingers()
  7185. })
  7186. .onActionUpdate(e => {
  7187. this.scaleValue = this.pinchValue * e.scale
  7188. })
  7189. .onActionStart(e => {
  7190. }))
  7191. .padding({
  7192. bottom: 0
  7193. })
  7194. }
  7195. setSonListTwoFingers() {
  7196. this.pinchValue = this.scaleValue;
  7197. Logger.info('this.pinchValue = ' + this.pinchValue);
  7198. if (this.pinchValue >= 1) {
  7199. this.sonTwoFingerType++
  7200. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  7201. if (this.sonTwoFingerType > 3) {
  7202. this.sonTwoFingerType = 1
  7203. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  7204. }
  7205. } else {
  7206. this.sonTwoFingerType--
  7207. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  7208. if (this.sonTwoFingerType < 1) {
  7209. this.sonTwoFingerType = 1
  7210. }
  7211. }
  7212. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  7213. this.pinchValue = 1;
  7214. this.scaleValue = 1;
  7215. }
  7216. @State sonTwoFingerType:number = 3
  7217. @Builder
  7218. private MusicItemSon(item: VideoItem, index?: number) {
  7219. Button({ type: ButtonType.Normal, stateEffect: true }) {
  7220. Row() {
  7221. Stack() {
  7222. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  7223. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7224. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7225. .alt($r('app.media.music_red'))
  7226. .fillColor(this.themeColor)
  7227. .borderRadius('100%')
  7228. .clip(true)
  7229. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  7230. .draggable(false)// 禁止长按手势拖动
  7231. .autoResize(true) // 重采样,可减少内存占用
  7232. .margin({ left: 20 })
  7233. }
  7234. .width('15%')
  7235. Column() {
  7236. Column() {
  7237. Text(this.isShowFileName?item.fileName :item.name)
  7238. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  7239. .fontColor(this.curIndex === index ? this.themeColor :
  7240. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  7241. .maxLines(1)
  7242. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  7243. Row() {
  7244. Column(){
  7245. Text(item.md5Str?.includes('Lossless')?
  7246. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  7247. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  7248. .padding({ top: 3,right:6,left:6,bottom:3 })
  7249. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  7250. $r('app.color.text_color'))
  7251. .fontWeight(500)
  7252. .borderRadius(12)
  7253. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  7254. .backgroundColor('#FFC107')
  7255. }
  7256. .padding({ top: 8 })
  7257. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  7258. item.artist + ' ' + item?.duration)
  7259. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7260. .padding({ top: 8 })
  7261. .maxLines(1)
  7262. .fontColor(this.curIndex === index ? this.themeColor :
  7263. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7264. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  7265. Blank()
  7266. Text(item.size)
  7267. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7268. .padding({ top: 8 })
  7269. .maxLines(1)
  7270. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  7271. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  7272. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7273. .margin({ left: 10 })
  7274. }
  7275. }
  7276. .height('100%')
  7277. .width('100%')
  7278. .justifyContent(FlexAlign.Center)
  7279. .alignItems(HorizontalAlign.Start)
  7280. }
  7281. .height('100%')
  7282. .width('65%')
  7283. Column() {
  7284. ImageAnimator()
  7285. .images(this.imagesF)// 动画数组
  7286. .duration(1000)// 持续
  7287. .state(this.animationState)// 动画状态
  7288. .fillMode(FillMode.Forwards)
  7289. .width(18)
  7290. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  7291. Visibility.None)
  7292. .height(18)
  7293. .iterations(-1) // 播放次数
  7294. }
  7295. .width('20%')
  7296. }
  7297. }
  7298. .backgroundColor(Color.Transparent)
  7299. .width('100%')
  7300. .reuseId('son_item')
  7301. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  7302. .shadow(this.scaleItem === index ? {
  7303. radius: 70,
  7304. color: '#15000000',
  7305. offsetX: 0,
  7306. offsetY: 0
  7307. } :
  7308. {
  7309. radius: 0,
  7310. color: '#15000000',
  7311. offsetX: 0,
  7312. offsetY: 0
  7313. })
  7314. .animation({ curve: Curve.Sharp, duration: 300 })
  7315. }
  7316. @Builder
  7317. MusicPlayBuilder() {
  7318. Column() {
  7319. this.IjkMusicPlayerView()
  7320. }
  7321. .transition(TransitionEffect.asymmetric(
  7322. TransitionEffect.opacity(1),
  7323. TransitionEffect.OPACITY
  7324. ))
  7325. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  7326. new hdsEffect.HdsEffectBuilder()
  7327. .shaderEffect({
  7328. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  7329. animation: {
  7330. duration: 10000,
  7331. iterations: -1,
  7332. autoPlay: true,
  7333. onFinish: ()=> {
  7334. console.info('Succeeded in finishing');
  7335. }
  7336. },
  7337. controller: this.bgController,
  7338. })
  7339. .buildEffect():null)
  7340. .height('100%')
  7341. .width('100%')
  7342. .onDisAppear(() => {
  7343. this.translateY = 0;
  7344. })
  7345. .translate({ y: this.translateY })
  7346. .gesture(
  7347. PanGesture(this.panOption)
  7348. .onActionUpdate((event?: GestureEvent) => {
  7349. if (event) {
  7350. // 只允许向下滑动,向上滑动时限制为0
  7351. this.translateY = Math.max(0, event.offsetY);
  7352. }
  7353. })
  7354. .onActionEnd((event?: GestureEvent) => {
  7355. // 使用更低的阈值和滑动速度判断
  7356. const minDistance = 100; // 最小滑动距离 100vp
  7357. const minVelocity = 500; // 最小滑动速度
  7358. // 获取滑动速度(如果可用)
  7359. const velocity = event?.velocityY || 0;
  7360. // 判断是否应该关闭:距离足够 或者 速度足够快
  7361. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  7362. if (shouldClose) {
  7363. // 添加关闭动画
  7364. this.getUIContext().animateTo({
  7365. duration: 300,
  7366. curve: Curve.Smooth
  7367. }, () => {
  7368. this.isShowPlay = false;
  7369. this.translateY = 0;
  7370. })
  7371. } else {
  7372. // 回弹动画
  7373. this.getUIContext().animateTo({
  7374. duration: 300,
  7375. curve: Curve.Smooth
  7376. }, () => {
  7377. this.translateY = 0;
  7378. })
  7379. }
  7380. })
  7381. )
  7382. }
  7383. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  7384. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  7385. HeightBreakpoint.HEIGHT_LG;
  7386. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  7387. @State topBarHeight: number = 50
  7388. @State barOpacity: number = 1
  7389. @State barBottomOpacity: number = 1
  7390. private hideDone: boolean = false;
  7391. @State currentYOffset: number = 0;
  7392. @State bottomBarHeight: number = 68;
  7393. private isHiding: boolean = false;
  7394. //是否是Pura X外屏,或者小屏幕
  7395. isPuraWP() {
  7396. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  7397. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  7398. }
  7399. //是否是Pura X外屏,或者小屏幕,手机横屏
  7400. /**
  7401. * 是否是Pura X外屏,或者小屏幕,手机横屏
  7402. * @returns
  7403. */
  7404. isCoverOpacity() {
  7405. if (this.isPuraWP()) {
  7406. return true
  7407. }
  7408. if (this.isPhoneLan()) {
  7409. return true
  7410. }
  7411. if (deviceInfo.marketName.includes('Pura X')
  7412. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  7413. return true
  7414. }
  7415. return false
  7416. }
  7417. //是不是手机横屏
  7418. isPhoneLan() {
  7419. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  7420. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  7421. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  7422. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  7423. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  7424. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  7425. if (this.isHiCarKuanBianPing()) {
  7426. return true
  7427. }
  7428. if (this.isHiCar()) {
  7429. return false
  7430. }
  7431. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7432. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  7433. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  7434. return true
  7435. }
  7436. return false
  7437. }
  7438. //是不是1920x720的hicar的屏幕分辨率
  7439. isHiCarKuanBianPing(){
  7440. if(!this.isHiCar()){
  7441. return false
  7442. }
  7443. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7444. { ratio: 1920 / 720, name: "1920x720" },
  7445. ];
  7446. const currentRatio: number = this.windowWidth / this.windowHeight;
  7447. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7448. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  7449. for (const hiCarRatio of hiCarAspectRatios) {
  7450. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  7451. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7452. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7453. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7454. //宽扁平的尺寸设置列表展示
  7455. this.twoFingerType ==3
  7456. this.isGridMusic = false
  7457. return true;
  7458. }
  7459. }
  7460. return false;
  7461. }
  7462. //是不是hicar的屏幕分辨率
  7463. isHiCarSmall() {
  7464. if(!this.isHiCar()){
  7465. return false
  7466. }
  7467. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  7468. {
  7469. this.columns = 6
  7470. return false
  7471. }
  7472. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7473. { ratio: 800 / 480, name: "800x480" },
  7474. { ratio: 1280 / 720, name: "1280x720" },
  7475. { ratio: 1920 / 1080, name: "1920x1080" },
  7476. ];
  7477. const currentRatio: number = this.windowWidth / this.windowHeight;
  7478. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7479. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  7480. for (const hiCarRatio of hiCarAspectRatios) {
  7481. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  7482. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7483. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  7484. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7485. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7486. //宽扁平的尺寸设置列表展示
  7487. return true;
  7488. }
  7489. }
  7490. return false;
  7491. }
  7492. isHiCar() {
  7493. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  7494. }
  7495. //是不是正常的手机竖屏
  7496. isPhonePortrait() {
  7497. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  7498. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  7499. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  7500. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7501. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  7502. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  7503. return true
  7504. }
  7505. return false
  7506. }
  7507. @State showSpeedDialog: boolean = false
  7508. @State longPressSpeed: number = 3 //长按默认倍数
  7509. @Builder
  7510. SpeedDialog() {
  7511. Stack() {
  7512. Column() {
  7513. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7514. .fontColor(Color.White)
  7515. .visibility(Visibility.Hidden)
  7516. }
  7517. .backgroundColor(Color.Black)
  7518. .borderRadius(20)
  7519. .padding({
  7520. top: 10,
  7521. right: 20,
  7522. left: 15,
  7523. bottom: 20
  7524. })
  7525. .opacity(0.6)
  7526. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7527. .fontColor(Color.White)
  7528. }
  7529. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  7530. .zIndex(5)
  7531. .margin({ top: 80 })
  7532. }
  7533. @Builder
  7534. IjkMusicPlayerView() {
  7535. Stack() {
  7536. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  7537. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  7538. HdsVisualComponent()
  7539. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  7540. console.info('Succeeded in finishing');
  7541. })
  7542. .width('100%')
  7543. .height('100%')
  7544. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  7545. }
  7546. Column() {
  7547. Column() {
  7548. //播放标题
  7549. Column() {
  7550. this.PlayTitle()
  7551. }
  7552. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  7553. .width('100%')
  7554. .margin({ top: 0 })
  7555. .height(PlayConstants.HEIGHT)
  7556. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  7557. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  7558. if (this.showSpeedDialog) {
  7559. this.SpeedDialog()
  7560. }
  7561. Stack() {
  7562. //手势拖动快进
  7563. Column()
  7564. .width(CommonConstants.FULL_PERCENT)
  7565. .height('100%')
  7566. .gesture(
  7567. GestureGroup(GestureMode.Parallel,
  7568. // 长按屏幕倍数播放
  7569. LongPressGesture({ repeat: true })
  7570. .onAction(() => {
  7571. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7572. this.showSpeedDialog = true;
  7573. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  7574. }
  7575. })
  7576. .onActionEnd(() => {
  7577. this.showSpeedDialog = false;
  7578. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7579. }),
  7580. //双击屏幕暂停或者播放
  7581. TapGesture({ count: 2 })
  7582. .onAction((event: GestureEvent) => {
  7583. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7584. ToastUtil.showToast('已暂停')
  7585. }
  7586. console.info('onecold playOrPause 6693')
  7587. this.playOrPause()
  7588. })
  7589. )
  7590. )
  7591. }
  7592. .height('65%')
  7593. Swiper() {
  7594. this.CoverInfo()
  7595. this.PlayerLyrics()
  7596. }
  7597. .onChange((index: number) => {
  7598. this.currentSwiperIndex = index
  7599. })
  7600. .indicator(false)
  7601. .displayCount(new BreakpointType({
  7602. sm: 1,
  7603. md: 2,
  7604. lg: 2,
  7605. xl: 2,
  7606. xxl: 2
  7607. }).getValue(this.currentBreakpoint))
  7608. .clip(false)
  7609. .loop(false)
  7610. .autoPlay(false)
  7611. // .interval(8000)
  7612. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  7613. .height('100%')
  7614. .hitTestBehavior(HitTestMode.Transparent)
  7615. Image($r('app.media.icon_replay'))
  7616. .objectFit(ImageFit.Auto)
  7617. .width('120px')
  7618. .height('120px')
  7619. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  7620. .border({ width: 0 })
  7621. .visibility(Visibility.None)
  7622. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  7623. .onClick(() => {
  7624. console.info('onecold startPlayOrResumePlay 6744')
  7625. this.startPlayOrResumePlay();
  7626. })
  7627. }
  7628. .width(CommonConstants.FULL_PERCENT)
  7629. .height(CommonConstants.FULL_PERCENT)
  7630. .justifyContent(FlexAlign.End)
  7631. }
  7632. .justifyContent(FlexAlign.End)
  7633. .margin({ bottom: 8 })
  7634. }
  7635. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  7636. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  7637. .animation({
  7638. duration: 666,
  7639. curve: 'ease-in-out' // 可选动画曲线
  7640. })
  7641. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  7642. ? BlurStyle.NONE :
  7643. BlurStyle.BACKGROUND_ULTRA_THICK)
  7644. .hitTestBehavior(HitTestMode.Transparent)
  7645. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  7646. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  7647. .onClick(() => {
  7648. if(this.isHiCar())
  7649. return
  7650. if(this.is_auto_hide_progress){
  7651. this.is_auto_hide_progress = false
  7652. }
  7653. this.startAutoHide()
  7654. })
  7655. }
  7656. @State progressValue: number = 0;
  7657. @State currentTime: string = "00:00";
  7658. @State totalTime: string = "00:00";
  7659. @State loadingVisible: Visibility = Visibility.None;
  7660. @State replayVisible: Visibility = Visibility.None;
  7661. @State slideEnable: boolean = false;
  7662. @State aspRatio: number = 0.5;
  7663. @State mContext: object | undefined = undefined;
  7664. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  7665. @State mFirst: boolean = true;
  7666. @State mDestroyPage: boolean = false;
  7667. @State playSpeed: number = 1;
  7668. @State oldSeconds: number = 0;
  7669. @State isSeekTo: boolean = false;
  7670. @State isCurrentTime: boolean = false;
  7671. @State videoWidth: string = '100%';
  7672. @State videoHeight: string = '100%';
  7673. @State initAspectRatio: number = 1;
  7674. @State videoAspectRatio: number = this.initAspectRatio;
  7675. @State videoUrl: string = '';
  7676. private last: number = 0;
  7677. @State videoParentAspectRatio: number = this.initAspectRatio;
  7678. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  7679. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  7680. @State PROGRESS_MAX_VALUE: number = 100;
  7681. @State updateProgressTimer: number = 0;
  7682. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  7683. @State name: string = '';
  7684. // @State loop: boolean = false;
  7685. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  7686. @State multiple: string = '1.0X';
  7687. xcomponentController: XComponentController = new XComponentController()
  7688. private panOptionBright: PanGestureOptions =
  7689. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  7690. private panOptionVolume: PanGestureOptions =
  7691. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  7692. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  7693. //手势的音量控制和亮度控制
  7694. private positionX: number = PlayConstants.POSITION_X;
  7695. private positionY: number = PlayConstants.POSITION_Y;
  7696. private windowClass: window.Window = globalThis.windowClass
  7697. @State volume: number = 0.5;
  7698. @State volumeSmall: boolean = false
  7699. @State autoParseMusicName: boolean = true
  7700. @State isShowFileName: boolean = false
  7701. @State isLongNameRoLL: boolean = true//长歌名滚动
  7702. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  7703. @State bright: number = PlayConstants.BRIGHT;
  7704. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  7705. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  7706. @State screenWidth: number = 0
  7707. @State screenHeight: number = 0
  7708. @State statusBarHeight: number = 0
  7709. @State isYesFull: boolean = false
  7710. private seekValue: number = 0
  7711. @State isVideoLock: boolean = false; // Whether the video playback is locked
  7712. eventHub = getContext().eventHub;
  7713. //投播组件
  7714. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  7715. private castController: avSession.AVCastController | undefined = undefined;
  7716. @State isCastPlaying: boolean = false;
  7717. @State currentTime2: number = 0;
  7718. @State currentStringTime: string = '00:00';
  7719. @State duration: number = 0;
  7720. @State isReady: boolean = false;
  7721. @State durationTime: number = 0;
  7722. @State durationStringTime: string = '00:00';
  7723. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  7724. // @State isPlaying: boolean = false;
  7725. private castSeek: boolean = false;
  7726. private castItem: avSession.AVQueueItem | undefined = undefined;
  7727. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  7728. @State rotateAngle2: number = -9
  7729. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  7730. @State cover: string | undefined = '';
  7731. @State artist: string | undefined = ''
  7732. // 1.初始化controller
  7733. private lyricController: LyricController = new LyricController()
  7734. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  7735. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  7736. private parser = new LyricParser()
  7737. @State randomColor: string = 'rgb(0,0,0)'
  7738. @State randomShakenX: number = 0
  7739. @State randomShakenY: number = 0
  7740. @State lyricTextSize: number = 24
  7741. @State lyricContent: string = ''
  7742. @State isDebug: boolean = false
  7743. @State isHightLightCenter: boolean = true
  7744. /**
  7745. * 初始化歌词加载与展示逻辑
  7746. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  7747. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  7748. * @param isApi2 是否使用API2获取歌词(可选)
  7749. *
  7750. * 主要流程:
  7751. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  7752. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  7753. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  7754. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  7755. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  7756. * 6. 解析失败或读取失败时,清空歌词显示。
  7757. *
  7758. * 注意事项:
  7759. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  7760. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  7761. * - 歌词内容解析后通过lyricController驱动UI渲染。
  7762. */
  7763. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  7764. if (StrUtil.isEmpty(lyricPath)) {
  7765. return
  7766. }
  7767. this.initPipLyricSetting()
  7768. this.lyricControllerSingle
  7769. .setTextSize(15)
  7770. .setCacheSize(4)
  7771. .setTextColor("#FFFFFF")
  7772. .setHighlightColor("#FFFFFF")
  7773. .setHighlightScale(1.2)
  7774. .setEmptyHint("")
  7775. .setAlignMode('center')
  7776. .setAnimationDuration(500)
  7777. .setSingleLine(true)
  7778. this.lyricContent = ''
  7779. this.lyricController
  7780. .setTextSize(this.currentLyricSize)
  7781. .setCacheSize(4)
  7782. .setTextColor("#DDDDDD")
  7783. .setHighlightColor("#FFFFFF")
  7784. .setEmptyHint("")
  7785. .setAnimationDuration(1000)
  7786. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  7787. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  7788. this.setBlurDegree(this.blurDegree, false)
  7789. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  7790. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  7791. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  7792. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  7793. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  7794. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  7795. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  7796. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7797. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  7798. this.lyricController.setTextWeight(this.lyricTextWeight)
  7799. this.showSingleLyric = false
  7800. this.timeOffset = 0
  7801. this.lyricController.setLyric(null)
  7802. this.lyricControllerSingle.setLyric(null)
  7803. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  7804. console.log("onecold lyricPath =" + lyricPath)
  7805. let neiqianLrc = ''
  7806. let lyContent = this.currentSong?.lyricContent
  7807. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  7808. neiqianLrc = lyContent
  7809. }
  7810. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  7811. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  7812. //赋值给this.lyricContent,播控中心才可以显示歌词
  7813. this.lyricContent = neiqianLrc
  7814. // 将文件内容按行分割成字符串数组
  7815. let lines = neiqianLrc.split('\n').map(line => line.trim());
  7816. // 3.解析歌词
  7817. let lyric = this.parser.parse(lines);
  7818. // 4.设置歌词
  7819. this.lyricController.setLyric(lyric);
  7820. this.lyricControllerXF.setLyric(lyric)
  7821. this.lyricControllerSingle.setLyric(lyric)
  7822. return
  7823. }
  7824. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  7825. && !Utility.isVideoByExtension(this.videoUrl))) {
  7826. if (this.currentSong !== undefined) {
  7827. // ToastUtil.showShort('正在为你搜索在线歌词!')
  7828. //判断是不是赞助会员,是会员的话才开启歌词功能
  7829. // if (!this.isDebug) {
  7830. // if (!Utility.isNoble()) {
  7831. // LogUtil.debug("onecold 不是赞助会员")
  7832. // return
  7833. // }
  7834. // if(!Utility.isPassInstallTime(33)){
  7835. // LogUtil.debug("onecold not pass time")
  7836. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  7837. // return
  7838. // }
  7839. // }
  7840. let artist = this.currentSong?.artist
  7841. if (artist === undefined) {
  7842. artist = ''
  7843. }
  7844. if (isApi2 === undefined) {
  7845. isApi2 = false
  7846. }
  7847. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  7848. // LogUtil.debug("onecold res =" + res)
  7849. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7850. if (StrUtil.isNotEmpty(res)) {
  7851. this.lyricContent = res
  7852. let lines = res.split('\n').map(line => line.trim());
  7853. // 3.解析歌词
  7854. let lyric = this.parser.parse(lines);
  7855. // 4.设置歌词
  7856. this.lyricController.setLyric(lyric);
  7857. this.lyricControllerXF.setLyric(lyric)
  7858. this.lyricControllerSingle.setLyric(lyric)
  7859. this.showSingleLyric = true
  7860. // 4.保存歌词文件lyric到本地
  7861. //2025年8月28日歌词不再加密下载
  7862. this.saveDataToFile(res, lyricPath, false)
  7863. } else {
  7864. this.lyricController.setLyric(null)
  7865. this.lyricControllerXF.setLyric(null)
  7866. this.lyricControllerSingle.setLyric(null)
  7867. if (isOnLineAndToast) {
  7868. ToastUtil.showShort('未获取到歌词!')
  7869. }
  7870. }
  7871. } else {
  7872. this.lyricController.setLyric(null)
  7873. this.lyricControllerXF.setLyric(null)
  7874. this.lyricControllerSingle.setLyric(null)
  7875. if (isOnLineAndToast) {
  7876. ToastUtil.showShort('未获取到歌词!')
  7877. }
  7878. }
  7879. })
  7880. } else {
  7881. this.lyricController.setLyric(null)
  7882. this.lyricControllerXF.setLyric(null)
  7883. this.lyricControllerSingle.setLyric(null)
  7884. if (isOnLineAndToast) {
  7885. ToastUtil.showShort('未获取到歌词!')
  7886. }
  7887. }
  7888. return
  7889. }
  7890. try {
  7891. let isJiaMi = false;
  7892. let realLyricPath = lyricPath
  7893. if (FileUtil.accessSync(jiaMilyricPath)) {
  7894. isJiaMi = true
  7895. realLyricPath = jiaMilyricPath
  7896. console.info("onecold 找到加密本地歌词 ");
  7897. } else {
  7898. isJiaMi = false
  7899. realLyricPath = lyricPath
  7900. console.info("onecold 找到本地歌词 ");
  7901. }
  7902. // 3.读取文件内容并指定编码为 UTF-8
  7903. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7904. const stat = await fileIo.stat(file.fd);
  7905. const arrayBuffer = new ArrayBuffer(stat.size);
  7906. fs.read(file.fd, arrayBuffer)
  7907. .then((readLen: number) => {
  7908. console.info("read file data succeed");
  7909. // let buf = buffer.from(arrayBuffer, 0, readLen);
  7910. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7911. // 检查 buf 是否为空
  7912. if (buf.length === 0) {
  7913. throw new Error("Buffer is empty after reading the file");
  7914. }
  7915. try {
  7916. // 检测文件编码
  7917. // let detectedEncoding = chardet.detect(buf);
  7918. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  7919. let detectedEncoding = this.detect(arrayBuffer)
  7920. console.info("onecoldT Detected encoding: " + detectedEncoding);
  7921. // 使用检测到的编码解码,解决中文乱码问题
  7922. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7923. console.info("onecoldT Detected textDecoder: " + textDecoder);
  7924. let fileContent = textDecoder.decode(buf);
  7925. console.info(`onecoldT The content of file1: ${fileContent}`);
  7926. //解密
  7927. if (isJiaMi) {
  7928. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  7929. }
  7930. console.info(`onecold The content of file2: ${fileContent}`);
  7931. this.lyricContent = fileContent
  7932. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  7933. this.lyricConStr = fileContent
  7934. }
  7935. // 将文件内容按行分割成字符串数组
  7936. let lines = fileContent.split('\n').map(line => line.trim());
  7937. console.info(`onecold The content of file: ${fileContent}`);
  7938. // 3.解析歌词
  7939. let lyric = this.parser.parse(lines);
  7940. // 4.设置歌词
  7941. this.lyricController.setLyric(lyric);
  7942. this.lyricControllerXF.setLyric(lyric)
  7943. this.lyricControllerSingle.setLyric(lyric)
  7944. this.showSingleLyric = true
  7945. console.info(`The content of file: ${fileContent}`);
  7946. } catch (chardetError) {
  7947. console.error("chardet.detect failed with error: " + chardetError.message);
  7948. this.lyricController.setLyric(null);
  7949. this.lyricControllerXF.setLyric(null)
  7950. this.lyricControllerSingle.setLyric(null)
  7951. }
  7952. })
  7953. .catch((err: BusinessError) => {
  7954. this.lyricController.setLyric(null)
  7955. this.lyricControllerXF.setLyric(null)
  7956. this.lyricControllerSingle.setLyric(null)
  7957. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  7958. })
  7959. .catch((err: Error) => {
  7960. this.lyricController.setLyric(null)
  7961. this.lyricControllerXF.setLyric(null)
  7962. this.lyricControllerSingle.setLyric(null)
  7963. console.error("read file 2 data failed with error message: " + err.message);
  7964. })
  7965. .finally(() => {
  7966. fs.closeSync(file);
  7967. });
  7968. } catch (error) {
  7969. this.lyricController.setLyric(null)
  7970. this.lyricControllerSingle.setLyric(null)
  7971. this.lyricControllerXF.setLyric(null)
  7972. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  7973. }
  7974. }
  7975. detect(data: ArrayBuffer): string {
  7976. //创建检测对象
  7977. let detector: UniversalDetector = new UniversalDetector();
  7978. // 传入检测数据并实时判断编码格式
  7979. detector.handleData(data, 0, data.byteLength);
  7980. // 标记检测数据 读取结束
  7981. detector.dataEnd();
  7982. // 获取检测结果
  7983. let detected: string = detector.getDetectedCharset();
  7984. // 释放资源
  7985. detector.reset();
  7986. return detected;
  7987. }
  7988. //初始化悬浮歌词的自定义设置
  7989. initPipLyricSetting() {
  7990. this.lyricControllerXF
  7991. .setTextSize(this.currentLyricSize)
  7992. .setCacheSize(4)
  7993. .setTextColor("#DDDDDD")
  7994. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  7995. .setEmptyHint("")
  7996. .setAnimationDuration(1000)
  7997. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  7998. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  7999. this.setBlurDegree(this.blurDegreePip, true)
  8000. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  8001. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  8002. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  8003. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  8004. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  8005. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  8006. this.lyricControllerXF.setHightLightCenter(true)
  8007. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  8008. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8009. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8010. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  8011. if (this.pipBgIndex === 0) {
  8012. if (this.cover) {
  8013. this.pipBg = this.cover
  8014. } else {
  8015. this.pipBg = this.imageColor
  8016. }
  8017. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8018. }
  8019. }
  8020. //根据item返回歌词内容
  8021. async getLyricContent(item: VideoItem): Promise<string> {
  8022. let neiqianLrc = ''
  8023. let lyContent = item?.lyricContent
  8024. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  8025. neiqianLrc = lyContent
  8026. return neiqianLrc
  8027. }
  8028. try {
  8029. //取数据库里面的歌词lyContent
  8030. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  8031. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  8032. console.log("onecold Lyrics:", lyricContent);
  8033. neiqianLrc = lyricContent
  8034. return neiqianLrc
  8035. }
  8036. } catch (error) {
  8037. console.error("Error fetching lyrics:", error);
  8038. }
  8039. try {
  8040. let filePath = item.filePath;
  8041. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  8042. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  8043. let isJiaMi = false;
  8044. let realLyricPath = lyricPath;
  8045. if (FileUtil.accessSync(jiaMilyricPath)) {
  8046. isJiaMi = true;
  8047. realLyricPath = jiaMilyricPath;
  8048. console.info("onecold 找到加密本地歌词");
  8049. } else {
  8050. console.info("onecold 找到本地歌词");
  8051. }
  8052. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8053. const stat = await fileIo.stat(file.fd);
  8054. const arrayBuffer = new ArrayBuffer(stat.size);
  8055. const readLen = await fs.read(file.fd, arrayBuffer);
  8056. console.info("read file data succeed");
  8057. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8058. if (buf.length === 0) {
  8059. throw new Error("Buffer is empty after reading the file");
  8060. }
  8061. // let detectedEncoding = chardet.detect(buf);
  8062. let detectedEncoding = this.detect(arrayBuffer)
  8063. console.info("Detected encoding: " + detectedEncoding);
  8064. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8065. let fileContent = textDecoder.decode(buf);
  8066. console.info(`onecold The content of file1: ${fileContent}`);
  8067. if (isJiaMi) {
  8068. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  8069. }
  8070. console.info(`onecold The content of file2: ${fileContent}`);
  8071. fs.closeSync(file);
  8072. return fileContent;
  8073. } catch (error) {
  8074. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  8075. return '';
  8076. }
  8077. }
  8078. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  8079. if (StrUtil.isEmpty(filePath)) {
  8080. return
  8081. }
  8082. try {
  8083. //将content进行加密
  8084. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  8085. let lyricContent = ''
  8086. if (isJiaMi) {
  8087. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  8088. } else {
  8089. lyricContent = content
  8090. }
  8091. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  8092. // 清空文件内容
  8093. await fileIo.truncate(file.fd, 0);
  8094. await fileIo.write(file.fd, lyricContent);
  8095. await fileIo.close(file);
  8096. console.log('onecold lyric file Data saved successfully.');
  8097. } catch (error) {
  8098. console.error('onecold lyric file Failed to save data:', error);
  8099. }
  8100. }
  8101. // 定义开始旋转的方法
  8102. // 定时器用于一百毫秒执行一次旋转角度
  8103. @State timer: number = 0
  8104. @State rotateAngle: number = 0
  8105. //封面旋转动画
  8106. animationRoFun() {
  8107. if (this.isPlaying && !this.isCoverRectangle) {
  8108. this.timer = setInterval(() => {
  8109. this.rotateAngle += 1
  8110. }, 100)
  8111. this.startRotation()
  8112. } else {
  8113. clearInterval(this.timer)
  8114. this.stopRotation()
  8115. }
  8116. }
  8117. // 定义开始旋转的方法
  8118. startRotation() {
  8119. if (this.isPlaying) {
  8120. animateTo({
  8121. duration: 777,
  8122. iterations: 1,
  8123. curve: Curve.Linear
  8124. }, () => {
  8125. this.rotateAngle2 = -9
  8126. })
  8127. }
  8128. }
  8129. // 回调,暂停和播放按钮回调,下一首和上一首
  8130. playChange() {
  8131. // if(this.isCoverRectangle){
  8132. // return
  8133. // }
  8134. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8135. this.setIsPlaying(true)
  8136. this.animationState = AnimationStatus.Running
  8137. } else {
  8138. this.setIsPlaying(false)
  8139. this.animationState = AnimationStatus.Paused
  8140. }
  8141. }
  8142. // 定义停止旋转的方法
  8143. stopRotation() {
  8144. if (this.isCoverRectangle) {
  8145. this.rotateAngle = 0
  8146. } else {
  8147. //唱针以左上角为点选择逆时针40度
  8148. animateTo({
  8149. duration: 1000,
  8150. curve: Curve.Linear,
  8151. iterations: 1,
  8152. }, () => {
  8153. this.rotateAngle2 = -45;
  8154. });
  8155. }
  8156. }
  8157. @Builder
  8158. private LyricsTopItem() {
  8159. Row() {
  8160. Stack() {
  8161. Image(this.cover)
  8162. .height(58)
  8163. .width(58)
  8164. .alt($r('app.media.alt'))
  8165. .borderRadius(8)
  8166. .clickEffect({ level: ClickEffectLevel.HEAVY })
  8167. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  8168. .shadow({
  8169. radius: 22,
  8170. type: ShadowType.BLUR,
  8171. color: 'on_primary'
  8172. })
  8173. }
  8174. .width('18%')
  8175. Column() {
  8176. Column() {
  8177. Text(this.name)
  8178. .fontSize(16)
  8179. .maxLines(1)
  8180. .fontWeight(FontWeight.Bolder)
  8181. .fontColor(this.currentLyricColor)
  8182. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8183. Row() {
  8184. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  8185. .fontSize(13)
  8186. .fontWeight(FontWeight.Bold)
  8187. .padding({ top: 8 })
  8188. .fontColor(this.currentLyricColor)
  8189. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8190. Blank()
  8191. }
  8192. }
  8193. .height('100%')
  8194. .width('100%')
  8195. .justifyContent(FlexAlign.Center)
  8196. .alignItems(HorizontalAlign.Start)
  8197. }
  8198. .height('100%')
  8199. .width('65%')
  8200. Column() {
  8201. Image($r('app.media.lyric'))
  8202. .width(28)
  8203. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8204. .margin({ right: 30 })
  8205. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8206. .onClick(() => {
  8207. this.isLyricSetting = !this.isLyricSetting;
  8208. })
  8209. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  8210. height: '95%',
  8211. dragBar: true,
  8212. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8213. showClose: true,
  8214. blurStyle: BlurStyle.Thin,
  8215. backgroundColor: Color.Transparent,
  8216. // title: { title: $r('app.string.lyric_setting') }
  8217. })
  8218. }
  8219. .width('18%')
  8220. }
  8221. .width('82%')
  8222. .height(58)
  8223. .justifyContent(FlexAlign.SpaceBetween)
  8224. }
  8225. //歌词显示
  8226. @Builder
  8227. PlayerLyrics() {
  8228. Column() {
  8229. Column() {
  8230. this.LyricsTopItem()
  8231. }
  8232. .height(this.isPuraWP() ? 15 : 58)
  8233. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  8234. Visibility.None : Visibility.Visible)
  8235. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  8236. .width("100%")
  8237. Column() {
  8238. LyricView2({
  8239. controller: this.lyricController,
  8240. enableSeek: true,
  8241. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8242. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8243. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8244. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  8245. if (!this.isPlaying) {
  8246. console.info('onecold startPlayOrResumePlay 7527')
  8247. this.startPlayOrResumePlay()
  8248. }
  8249. else {
  8250. this.isSeekTo = true;
  8251. this.mDestroyPage = false;
  8252. this.showLoadIng();
  8253. this.seekTo(position + "");
  8254. this.isSeekTo = false;
  8255. }
  8256. return true
  8257. }
  8258. })
  8259. .width("100%")
  8260. .layoutWeight(1)
  8261. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  8262. if (this.isPhoneLan()) {
  8263. Column() {
  8264. this.playProgressView()
  8265. // this.playCenterView()
  8266. }
  8267. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  8268. }
  8269. }
  8270. .position({
  8271. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  8272. (this.isPuraWP() ? 58 : 99)
  8273. })
  8274. .justifyContent(FlexAlign.Center)
  8275. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  8276. }
  8277. }
  8278. @Builder
  8279. SingleLyricView() {
  8280. Column() {
  8281. Column() {
  8282. LyricView2({
  8283. controller: this.lyricControllerSingle,
  8284. enableSeek: false,
  8285. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8286. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8287. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8288. })
  8289. }
  8290. .height(66)
  8291. .margin({ bottom: 20 })
  8292. }
  8293. }
  8294. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  8295. @Builder
  8296. BottomControl() {
  8297. Column() {
  8298. this.TopPlayProgressView()
  8299. //播放 暂停,下一首,上一首
  8300. this.playCenterView()
  8301. //播放进度条
  8302. this.BottomView()
  8303. }
  8304. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  8305. }
  8306. //播放控制上一首 下一首 暂停和播放
  8307. @Builder
  8308. playCenterView(){
  8309. Row() {
  8310. Button({type:ButtonType.Circle,stateEffect:true}){
  8311. //更多功能
  8312. Image($r('app.media.menu'))
  8313. .width(24)
  8314. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8315. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  8316. height: '99%',
  8317. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  8318. dragBar: true,
  8319. showClose: true,
  8320. blurStyle: BlurStyle.Thin,
  8321. backgroundColor: Color.Transparent,
  8322. })
  8323. }
  8324. .height(45)
  8325. .width(45)
  8326. .margin({ left: 5 })
  8327. .backgroundColor(Color.Transparent)
  8328. .onClick(() => {
  8329. this.isShowMoreView = !this.isShowMoreView;
  8330. })
  8331. Button({type:ButtonType.Circle,stateEffect:true}){
  8332. Image($r('app.media.ic_previous'))
  8333. .width(33)
  8334. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8335. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8336. }
  8337. .height(45)
  8338. .width(45)
  8339. .onClick(async () => {
  8340. await this.playPrevious()
  8341. })
  8342. .backgroundColor(Color.Transparent)
  8343. Button({type:ButtonType.Circle,stateEffect:true}){
  8344. Column() {
  8345. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  8346. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  8347. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  8348. .width(this.isPhoneLan()?45:55)
  8349. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8350. .fillColor(Color.White)
  8351. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8352. }
  8353. }
  8354. .onClick(async () => {
  8355. this.playOrPause()
  8356. })
  8357. .backgroundColor(Color.Transparent)
  8358. .layoutWeight(1)
  8359. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8360. Image($r('app.media.ic_next'))
  8361. .width(33)
  8362. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8363. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8364. }
  8365. .height(45)
  8366. .width(45)
  8367. .backgroundColor(Color.Transparent)
  8368. .onClick(async () => {
  8369. await this.playNext();
  8370. })
  8371. this.fullButton()
  8372. }
  8373. .width('95%')
  8374. .margin({ bottom:this.isCoverOpacity()?0:15 })
  8375. .justifyContent(FlexAlign.SpaceEvenly)
  8376. }
  8377. @Builder
  8378. TopPlayProgressView(){
  8379. Row() {
  8380. Column(){
  8381. Row(){
  8382. Stack(){
  8383. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  8384. .fontColor([Color.White])
  8385. .fontSize(21)
  8386. .effectStrategy(1)
  8387. Text(this.fastForwardSeconds)
  8388. .fontColor(Color.White)
  8389. .fontSize(10)
  8390. .fontWeight(FontWeight.Bold)
  8391. }
  8392. .margin({left:12,bottom:6})
  8393. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8394. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8395. .onClick(()=>{
  8396. this.backForward()
  8397. })
  8398. Slider({
  8399. value: this.progressValue,
  8400. min: 0,
  8401. max: this.PROGRESS_MAX_VALUE,
  8402. step: 1,
  8403. style: SliderStyle.InSet
  8404. })
  8405. .height(20)
  8406. .blockColor('rgba(255,255,255,1)')
  8407. .trackColor('rgba(255,255,255,0.3)')
  8408. .selectedColor(Color.White)
  8409. .trackThickness(4)
  8410. .layoutWeight(1)
  8411. .showSteps(false)
  8412. .showTips(true)
  8413. .alignSelf(ItemAlign.Center)
  8414. .enabled(this.slideEnable)
  8415. .onChange((value: number, mode: SliderChangeMode) => {
  8416. // if (mode == 2) {
  8417. this.isSeekTo = true;
  8418. this.mDestroyPage = false;
  8419. this.showLoadIng();
  8420. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8421. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8422. this.seekTo(seekValue + "");
  8423. // this.setProgress()
  8424. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8425. this.isSeekTo = false;
  8426. // }
  8427. })
  8428. Stack(){
  8429. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  8430. .fontColor([Color.White])
  8431. .fontSize(21)
  8432. .effectStrategy(1)
  8433. Text(this.fastForwardSeconds)
  8434. .fontColor(Color.White)
  8435. .fontSize(10)
  8436. .fontWeight(FontWeight.Bold)
  8437. }
  8438. .margin({right:10,bottom:6})
  8439. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8440. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8441. .onClick(()=>{
  8442. this.fastForward()
  8443. })
  8444. }
  8445. .padding({ right: 7,left:22 })
  8446. Row(){
  8447. Text(this.currentTime)
  8448. .fontSize(10)
  8449. .fontColor(Color.White)
  8450. Blank()
  8451. .layoutWeight(1)
  8452. Text(this.totalTime)
  8453. .fontSize(10)
  8454. .fontColor(Color.White)
  8455. }
  8456. .justifyContent(FlexAlign.Start)
  8457. .padding({ right: 18,left:36 })
  8458. }
  8459. }
  8460. //x5的竖屏模式需要99%
  8461. .width(this.isLandscape?'80%':'93%')
  8462. .justifyContent(FlexAlign.Center)
  8463. .margin({bottom:3})
  8464. .animation({
  8465. duration: 666,
  8466. curve: 'ease-in-out' // 可选动画曲线
  8467. })
  8468. }
  8469. //播放进度条
  8470. @Builder
  8471. BottomView(){
  8472. Row() {
  8473. Button({type:ButtonType.Circle,stateEffect:true}){
  8474. Column() {
  8475. if (this.playType === 0) {
  8476. Image($r('app.media.loop'))
  8477. .width(27)
  8478. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8479. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8480. } else if (this.playType === 1) {
  8481. Image($r('app.media.single'))
  8482. .width(27)
  8483. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8484. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8485. } else if (this.playType === 2) {
  8486. Image($r('app.media.normal_play'))
  8487. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8488. .width(27)
  8489. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8490. } else if (this.playType === 3) {
  8491. Image($r('app.media.random'))
  8492. .width(27)
  8493. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8494. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8495. }
  8496. }
  8497. }
  8498. .layoutWeight(1)
  8499. .margin({ left: 5 })
  8500. .height(45)
  8501. .width(45)
  8502. .backgroundColor(Color.Transparent)
  8503. .onClick(async () => {
  8504. this.setLoopMode()
  8505. })
  8506. if(this.currentSong){
  8507. Button({type:ButtonType.Circle,stateEffect:true}){
  8508. Column() {
  8509. Image($r('app.media.rename2'))
  8510. .width(21)
  8511. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8512. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8513. }
  8514. }
  8515. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  8516. height: '99%',
  8517. dragBar: true,
  8518. showClose: true,
  8519. preferType: SheetType.BOTTOM,
  8520. title: { title: '编辑标签' }
  8521. })
  8522. .height(45)
  8523. .width(45)
  8524. .layoutWeight(1)
  8525. .backgroundColor(Color.Transparent)
  8526. .onClick(async () => {
  8527. this.setEditStrEmpty()
  8528. this.tempLyricContent = this.lyricContent
  8529. this.isShowEdit = !this.isShowEdit;
  8530. })
  8531. }
  8532. Button({type:ButtonType.Circle,stateEffect:true}){
  8533. Column() {
  8534. Image($r('app.media.lyric'))
  8535. .width(26)
  8536. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8537. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8538. }
  8539. }
  8540. .height(45)
  8541. .width(45)
  8542. .layoutWeight(1)
  8543. .backgroundColor(Color.Transparent)
  8544. .onClick(async () => {
  8545. this.isLyricSetting = !this.isLyricSetting;
  8546. })
  8547. //播放列表
  8548. Button({type:ButtonType.Circle,stateEffect:true}){
  8549. Image($r('app.media.hm_playlist'))
  8550. .width(24)
  8551. .fillColor(Color.White)
  8552. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8553. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8554. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8555. height: '95%',
  8556. dragBar: true,
  8557. showClose: true,
  8558. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8559. blurStyle: BlurStyle.Thin,
  8560. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  8561. title: {
  8562. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8563. + `(${this.songList.length}首)`
  8564. }
  8565. })
  8566. }
  8567. .layoutWeight(1)
  8568. .height(45)
  8569. .width(45)
  8570. .backgroundColor(Color.Transparent)
  8571. .onClick(() => {
  8572. this.isShowSheetView = !this.isShowSheetView;
  8573. if(this.isPlayListBgGrass){
  8574. this.isFrontWhite = true
  8575. }else{
  8576. this.isFrontWhite = false
  8577. }
  8578. this.scrollIndex()
  8579. })
  8580. }
  8581. .width(this.isLandscape?'88%':'95%')
  8582. .justifyContent(FlexAlign.SpaceAround)
  8583. .height(30)
  8584. .animation({
  8585. duration: 666,
  8586. curve: 'ease-in-out' // 可选动画曲线
  8587. })
  8588. }
  8589. @Builder
  8590. fullButton(){
  8591. Button({type:ButtonType.Circle,stateEffect:true}){
  8592. Column() {
  8593. Image($r('app.media.full_4'))
  8594. .width(25)
  8595. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8596. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8597. }
  8598. }
  8599. .layoutWeight(1)
  8600. .backgroundColor(Color.Transparent)
  8601. .height(45)
  8602. .width(45)
  8603. .onClick(async () => {
  8604. if (this.isLandscape) {
  8605. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8606. } else {
  8607. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8608. }
  8609. })
  8610. }
  8611. //旧版本播放进度条
  8612. @Builder
  8613. playProgressView() {
  8614. Row() {
  8615. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8616. Column() {
  8617. if (this.playType === 0) {
  8618. Image($r('app.media.loop'))
  8619. .width($r('app.float.control_image_width'))
  8620. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8621. } else if (this.playType === 1) {
  8622. Image($r('app.media.single'))
  8623. .width($r('app.float.control_image_width'))
  8624. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8625. } else if (this.playType === 2) {
  8626. Image($r('app.media.normal_play'))
  8627. .width($r('app.float.control_image_width'))
  8628. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8629. } else if (this.playType === 3) {
  8630. Image($r('app.media.random'))
  8631. .width($r('app.float.control_image_width'))
  8632. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8633. }
  8634. }
  8635. }
  8636. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8637. .animation({
  8638. duration: 666,
  8639. curve: 'ease-in-out' // 可选动画曲线
  8640. })
  8641. .backgroundColor(Color.Transparent)
  8642. .margin({ right: 10 })
  8643. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8644. .onClick(async () => {
  8645. this.setLoopMode()
  8646. })
  8647. Text(this.currentTime)
  8648. .fontSize($r('app.float.slider_font_size'))
  8649. .fontColor(Color.White)
  8650. .margin(3)
  8651. Slider({
  8652. value: this.progressValue,
  8653. min: 0,
  8654. max: this.PROGRESS_MAX_VALUE,
  8655. step: 1,
  8656. style: SliderStyle.OutSet
  8657. })
  8658. .width('600px')
  8659. .blockColor('rgba(255,255,255,1)')
  8660. .trackColor('rgba(255,255,255,0.3)')
  8661. .selectedColor(Color.White)
  8662. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  8663. .layoutWeight(1)
  8664. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8665. .showSteps(false)
  8666. .showTips(true)
  8667. .enabled(this.slideEnable)
  8668. .onChange((value: number, mode: SliderChangeMode) => {
  8669. // if (mode == 2) {
  8670. this.isSeekTo = true;
  8671. this.mDestroyPage = false;
  8672. this.showLoadIng();
  8673. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8674. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8675. this.seekTo(seekValue + "");
  8676. // this.setProgress()
  8677. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8678. this.isSeekTo = false;
  8679. // }
  8680. })
  8681. Text(this.totalTime)
  8682. .fontSize($r('app.float.slider_font_size'))
  8683. .fontColor(Color.White)
  8684. .margin(3)
  8685. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8686. //播放列表
  8687. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8688. Image($r('app.media.hm_playlist'))
  8689. .width($r('app.float.control_image_width'))
  8690. .fillColor(Color.White)
  8691. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8692. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8693. height: '95%',
  8694. dragBar: true,
  8695. showClose: true,
  8696. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8697. blurStyle: BlurStyle.Thin,
  8698. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  8699. title: {
  8700. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8701. + `(${this.songList.length}首)`
  8702. }
  8703. })
  8704. }
  8705. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8706. .animation({
  8707. duration: 666,
  8708. curve: 'ease-in-out' // 可选动画曲线
  8709. })
  8710. .backgroundColor(Color.Transparent)
  8711. .margin({ right: 20, left: 10 })
  8712. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8713. .onClick(() => {
  8714. this.isShowSheetView = !this.isShowSheetView;
  8715. if (this.isPlayListBgGrass) {
  8716. this.isFrontWhite = true
  8717. } else {
  8718. this.isFrontWhite = false
  8719. }
  8720. this.scrollIndex()
  8721. })
  8722. }
  8723. //x5的竖屏模式需要99%
  8724. .width(this.isPhonePortrait() ? '93.4%'
  8725. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  8726. .height(this.isPhoneLan() ? 25 : 33)
  8727. .animation({
  8728. duration: 666,
  8729. curve: 'ease-in-out' // 可选动画曲线
  8730. })
  8731. }
  8732. isBigScreen() {
  8733. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  8734. return true
  8735. }
  8736. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8737. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8738. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  8739. return false
  8740. } else {
  8741. return true
  8742. }
  8743. return false
  8744. }
  8745. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  8746. @State isCoverRectangle: boolean = false
  8747. @State isCoverTop: boolean = true
  8748. // 添加控制缩放的状态变量
  8749. @State scaleValueImage: number = 1
  8750. @Builder
  8751. CoverInfo() {
  8752. Column() {
  8753. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  8754. if (this.isCoverRectangle) {
  8755. if (!this.isCoverTop) {
  8756. this.musicNameInfo(false)
  8757. }
  8758. } else {
  8759. this.musicNameInfo(false)
  8760. }
  8761. Stack() {
  8762. // 唱片旋转效果
  8763. Image($r('app.media.ic_music_disc'))
  8764. .width(245)
  8765. .height(245)
  8766. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  8767. .aspectRatio(1)
  8768. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8769. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8770. .borderRadius('100%')
  8771. .align(Alignment.Center)
  8772. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  8773. .rotate({
  8774. angle: this.rotateAngle,
  8775. centerX: "50%",
  8776. centerY: "50%",
  8777. })
  8778. .animation({
  8779. duration: 100,
  8780. curve: Curve.Linear
  8781. })
  8782. .shadow({
  8783. radius: 22,
  8784. type: ShadowType.BLUR,
  8785. color: 'on_primary'
  8786. })
  8787. Column() {
  8788. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  8789. Image(this.cover)
  8790. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  8791. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  8792. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8793. .alt($r('app.media.alt'))
  8794. .margin({ right: 8, left: 8, top: 8 })
  8795. .aspectRatio(1)
  8796. .opacity(this.opacityValueImage)
  8797. .geometryTransition('cover') // 绑定标识符
  8798. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8799. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8800. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8801. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8802. .align(Alignment.Center)//
  8803. .clip(true)
  8804. .rotate({
  8805. x: 0,
  8806. y: 0,
  8807. z: 1,
  8808. angle: this.rotateAngle
  8809. })
  8810. .shadow({
  8811. radius: 22,
  8812. type: ShadowType.BLUR,
  8813. color: 'on_primary'
  8814. })
  8815. .onClick(() => {
  8816. })
  8817. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  8818. // .shaderEffect({
  8819. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  8820. // animation: {
  8821. // duration: 4000,
  8822. // iterations: -1,
  8823. // autoPlay: true,
  8824. // onFinish: () => {
  8825. // console.info('Succeeded in finishing');
  8826. // }
  8827. // },
  8828. // controller: this.controller,
  8829. // params: {
  8830. // firstEdgeFlowLight: {
  8831. // startPos: 0,
  8832. // endPos: 1.0,
  8833. // color: '#1AD0F1',
  8834. // },
  8835. // secondEdgeFlowLight: {
  8836. // startPos: 0.5,
  8837. // endPos: 1.5,
  8838. // color: '#FFA4E5',
  8839. // }
  8840. // }
  8841. // })
  8842. // .buildEffect())
  8843. this.musicNameInfo(false)
  8844. } else {
  8845. Image(this.cover)
  8846. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  8847. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  8848. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8849. .alt($r('app.media.alt'))
  8850. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  8851. .aspectRatio(1)
  8852. .opacity(this.opacityValueImage)
  8853. .geometryTransition('cover') // 绑定标识符
  8854. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8855. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8856. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8857. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8858. .align(Alignment.Center)//
  8859. .clip(true)
  8860. .shadow({
  8861. radius: 22,
  8862. type: ShadowType.BLUR,
  8863. color: 'on_primary'
  8864. })
  8865. .rotate({
  8866. x: 0,
  8867. y: 0,
  8868. z: 1,
  8869. angle: this.rotateAngle
  8870. })
  8871. .onClick(() => {
  8872. })
  8873. if (this.isPhoneLan()) {
  8874. Text(this.name)
  8875. .fontSize(18)
  8876. .fontWeight(FontWeight.Bold)
  8877. .margin({ top: 13 })
  8878. .textOverflow({ overflow: TextOverflow.Ellipsis })
  8879. .maxLines(1)
  8880. .width('99%')
  8881. .textAlign(TextAlign.Center)
  8882. .fontColor(Color.White)
  8883. }
  8884. }
  8885. }
  8886. // 唱针以左上角为点选择逆时针40度
  8887. Image($r('app.media.ic_music_cover_hand'))
  8888. .height(130)
  8889. .margin({ bottom: 220, top: 0 })
  8890. .align(Alignment.Top)
  8891. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  8892. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8893. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8894. Column({ space: 8 }) {
  8895. Text(this.name)
  8896. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  8897. .fontWeight(FontWeight.Bold)
  8898. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8899. .maxLines(1)
  8900. .width('48%')
  8901. .textAlign(TextAlign.Center)
  8902. .fontColor(Color.White)
  8903. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8904. Text(this.artist)
  8905. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  8906. .fontColor(Color.White)
  8907. .fontWeight(FontWeight.Bold)
  8908. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8909. }
  8910. .justifyContent(FlexAlign.Start)
  8911. .zIndex(1)
  8912. .geometryTransition('name')
  8913. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  8914. }
  8915. .margin({
  8916. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  8917. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  8918. top: this.isCoverOpacity() ? 0 : 20
  8919. })
  8920. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  8921. this.SingleLyricView()
  8922. }
  8923. if (this.isPhoneLan()) {
  8924. Column() {
  8925. this.playCenterView()
  8926. // this.playProgressView()
  8927. }
  8928. .position({ left: 28, bottom: 38 })
  8929. } else {
  8930. this.BottomControl()
  8931. }
  8932. }
  8933. .width(CommonConstants.FULL_PERCENT)
  8934. .clip(true)
  8935. }
  8936. @Builder
  8937. private musicNameInfo(isHidden: boolean) {
  8938. Row(){
  8939. Column({ space: 8 }) {
  8940. Text(this.name)
  8941. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  8942. .fontWeight(FontWeight.Bold)
  8943. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8944. .maxLines(1)
  8945. .width('99%')
  8946. .textAlign(TextAlign.Start)
  8947. .fontColor(Color.White)
  8948. Text(this.artist + ' ' + this.currentSong?.album)
  8949. .fontSize(this.isCoverOpacity() ? 12 : 15)
  8950. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8951. .fontColor(Color.White)
  8952. .textAlign(TextAlign.Start)
  8953. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  8954. .width('99%')
  8955. .maxLines(1)
  8956. }
  8957. .zIndex(1)
  8958. .geometryTransition('name') // 绑定标识符
  8959. .layoutWeight(1)
  8960. .margin({ left: 15 })
  8961. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8962. Blank()
  8963. Row(){
  8964. Button({type:ButtonType.Circle,stateEffect:true}){
  8965. //添加或取消收藏
  8966. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  8967. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  8968. .fontSize(22)
  8969. .fontColor([Color.White])
  8970. .alignSelf(ItemAlign.Center)
  8971. // .width(24)
  8972. .clickEffect({level:ClickEffectLevel.MIDDLE})
  8973. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8974. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8975. .onClick(async () => {
  8976. if(this.currentSong){
  8977. this.doFav(this.currentSong)
  8978. }
  8979. })
  8980. }
  8981. .margin({ left: 15,right:3 })
  8982. .backgroundColor(Color.Transparent)
  8983. .width(45)
  8984. .height(45)
  8985. }
  8986. }
  8987. .width('90%')
  8988. .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
  8989. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  8990. }
  8991. @Builder
  8992. private PlayTitle() {
  8993. Row() {
  8994. Row() {
  8995. Image($r('app.media.ic_back_down'))
  8996. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  8997. .hitTestBehavior(HitTestMode.Transparent)
  8998. Text(this.name + ' ' + this.artist)
  8999. .fontColor(Color.White)
  9000. .fontSize($r('app.float.title_font_size'))
  9001. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9002. .maxLines(1)
  9003. .visibility(Visibility.None)
  9004. .margin({ left: 2, right: 30 })
  9005. }
  9006. .layoutWeight(1)
  9007. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9008. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  9009. .onClick(() => {
  9010. this.setShowPlayPage()
  9011. })
  9012. Column() {
  9013. AVCastPicker({
  9014. normalColor: Color.White,
  9015. onStateChange: this.onStateVastChange
  9016. })
  9017. .width(24)
  9018. .height(24)
  9019. }
  9020. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  9021. }
  9022. .width(PlayConstants.ROW_WIDTH)
  9023. }
  9024. @Builder
  9025. lyricSettingSheet(isPip: boolean) {
  9026. Scroll() {
  9027. this.lyricSetting(isPip)
  9028. }
  9029. .width('100%')
  9030. .height('100%')
  9031. }
  9032. @Builder
  9033. lyricSetting(isPip: boolean) {
  9034. Column() {
  9035. // 时间调节模块
  9036. if (!isPip) {
  9037. this.BuildTimeControls()
  9038. }
  9039. // 字号控制模块
  9040. this.BuildFontControls(isPip)
  9041. }
  9042. }
  9043. // 歌词时间偏移状态
  9044. @State timeOffset: number = 0.0
  9045. @State currentLyricColor: string = '#FFFFFF'
  9046. @State currentLyricColorPip: string = '#FFFFFF'
  9047. @State currentHighLightLyricColor: string = '#FF4081'
  9048. @State currentHighLightLyricColorPip: string = '#FF4081'
  9049. // 歌词字号状态
  9050. @State currentLyricSize: number = 20
  9051. @State currentLyricSizePip: number = 20
  9052. // 高亮歌词放大倍数
  9053. @State currentHightLyricSize: number = 1.2
  9054. @State currentHightLyricSizePip: number = 1.2
  9055. @State currentLyricLineSpace: number = 10
  9056. @State currentLyricLineSpacePip: number = 10
  9057. @State currentLyricAlignMode: number = 1
  9058. @State currentLyricAlignModePip: number = 1
  9059. @State blurDegree: number = 2
  9060. @State blurDegreePip: number = 2
  9061. @State isShowSelectColor: boolean = false
  9062. @State isShowHLSelectColor: boolean = false
  9063. @State isShowPipBgSelectColor: boolean = false
  9064. @State pipLyWidth: number = 330
  9065. @State pipLyHeight: number = 120
  9066. // 构建颜色选择器
  9067. @Builder
  9068. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  9069. Row({ space: 10 }) {
  9070. HSBColorPicker({
  9071. color: '#FFFFFF',
  9072. radius: 8,
  9073. layout: HSBColorPickerLayout.COLUMN,
  9074. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  9075. '#fa7105'],
  9076. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  9077. this.changeLyricColor(value, isPip, isBGPip)
  9078. })
  9079. .height(250)
  9080. .layoutWeight(1)
  9081. .padding(25)
  9082. }
  9083. .width('66%')
  9084. }
  9085. @State isOpenPip: boolean = false
  9086. @State pipBgIndex: number = 0
  9087. // 构建字号控制器
  9088. @Builder
  9089. BuildFontControls(isPip: boolean) {
  9090. Column() {
  9091. if (isPip) {
  9092. Column() {
  9093. Row() {
  9094. Text('悬浮歌词')
  9095. .margin({ left: 18 })
  9096. .fontSize(15)
  9097. .fontColor(Color.White)
  9098. .fontWeight(480)
  9099. .layoutWeight(1)
  9100. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  9101. .selectedColor(this.themeColor)
  9102. .switchPointColor(Color.White)
  9103. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9104. .margin({ right: 18 })
  9105. .onChange((checked: boolean) => {
  9106. this.isOpenPip = checked;
  9107. if (this.isOpenPip) {
  9108. this.startPip()
  9109. } else {
  9110. this.stopPip()
  9111. }
  9112. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  9113. })
  9114. .width(50)
  9115. .height(30);
  9116. }
  9117. .height(55)
  9118. }
  9119. .backgroundColor(Color.Transparent)
  9120. .borderRadius(15)
  9121. .margin({
  9122. left: 30,
  9123. right: 30,
  9124. top: 0,
  9125. bottom: 20
  9126. })
  9127. .padding(0)
  9128. .border({
  9129. color: Color.White,
  9130. width: 1.8
  9131. })
  9132. }else{
  9133. Column() {
  9134. Row() {
  9135. Text('单行歌词')
  9136. .margin({ left: 18 })
  9137. .fontSize(15)
  9138. .fontColor(Color.White)
  9139. .fontWeight(480)
  9140. .layoutWeight(1)
  9141. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  9142. .selectedColor(this.themeColor)
  9143. .switchPointColor(Color.White)
  9144. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9145. .margin({ right: 18 })
  9146. .onChange((checked: boolean) => {
  9147. this.isShowSingleLineLyric = checked;
  9148. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  9149. })
  9150. .width(50)
  9151. .height(30);
  9152. }
  9153. .height(55)
  9154. }
  9155. .backgroundColor(Color.Transparent)
  9156. .borderRadius(15)
  9157. .margin({
  9158. left: 30,
  9159. right: 30,
  9160. top: 10,
  9161. bottom: 10
  9162. })
  9163. .padding(0)
  9164. .border({
  9165. color: Color.White,
  9166. width: 1.8
  9167. })
  9168. }
  9169. Row() {
  9170. Text(`歌词居中:`)
  9171. .fontSize(14)
  9172. .fontColor(Color.White)
  9173. .margin({ left: 2 })
  9174. Row() {
  9175. ForEach(['居中', '居左'], (size: string, index: number) => {
  9176. Button(size)
  9177. .width(60)
  9178. .height(28)
  9179. .fontSize(12)
  9180. .fontColor('#FFFFFF')
  9181. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  9182. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  9183. .border({
  9184. color: (!isPip && this.currentLyricAlignMode === index) ||
  9185. (isPip && this.currentLyricAlignModePip === index) ?
  9186. '#007DFF' : '#DDDDDD',
  9187. width: 1.8
  9188. })
  9189. .onClick(() => {
  9190. this.setLyricAlignMode(index, isPip)
  9191. })
  9192. .margin({ left: 10, right: 8 })
  9193. })
  9194. }
  9195. .width('76%')
  9196. Blank()
  9197. }
  9198. .margin({
  9199. top: 10,
  9200. bottom: 10,
  9201. right: 20,
  9202. left: 20
  9203. })
  9204. if (isPip) {
  9205. Row() {
  9206. Text(`悬浮背景:`)
  9207. .fontSize(14)
  9208. .fontColor(Color.White)
  9209. Select([
  9210. { value: CommonConstants.PIP_LYRIC_BG[0] },
  9211. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  9212. .font({ size: 13, weight: FontWeight.Medium })
  9213. .fontColor(Color.White)
  9214. .margin({ left: 10 })
  9215. .selected(this.pipBgIndex)
  9216. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  9217. .onSelect(async (_index: number, text?: string | undefined) => {
  9218. this.pipBgIndex = _index
  9219. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  9220. if (this.pipBgIndex === 0) {
  9221. if (this.cover) {
  9222. this.pipBg = this.cover
  9223. } else {
  9224. this.pipBg = this.imageColor
  9225. }
  9226. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9227. } else {
  9228. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9229. }
  9230. })
  9231. Column() {
  9232. }
  9233. .backgroundColor(this.pipBg)
  9234. .margin({ left: 10, right: 10 })
  9235. .borderRadius(20)
  9236. .height(28)
  9237. .width(28)
  9238. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9239. Row() {
  9240. SymbolGlyph($r('sys.symbol.paintbrush'))
  9241. .fontColor([Color.White])
  9242. .effectStrategy(1)
  9243. Text(`选择颜色`)
  9244. .fontSize(13)
  9245. .margin({ left: 10 })
  9246. .fontColor(Color.White)
  9247. }
  9248. }
  9249. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  9250. .backgroundColor(Color.Transparent)
  9251. .border({
  9252. color: '#FFFFFF',
  9253. radius: 20,
  9254. width: 1.8
  9255. })
  9256. .height(36)
  9257. .width(110)
  9258. .onClick(() => {
  9259. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  9260. })
  9261. .bindPopup(this.isShowPipBgSelectColor, {
  9262. builder: this.SelectColor(false, isPip, true),
  9263. placement: Placement.Top,
  9264. mask: { color: '#33000000' },
  9265. enableArrow: false, //是否显示箭头
  9266. showInSubWindow: false,
  9267. onStateChange: (e) => {
  9268. if (!e.isVisible) {
  9269. this.isShowPipBgSelectColor = false
  9270. }
  9271. }
  9272. })
  9273. }
  9274. .width('76%')
  9275. .margin({ bottom: 5, right: 45, left: 20 })
  9276. }
  9277. if (!isPip) {
  9278. Row() {
  9279. Text(`高亮居中:`)
  9280. .fontSize(14)
  9281. .fontColor(Color.White)
  9282. Column() {
  9283. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  9284. .selectedColor(this.themeColor)
  9285. .switchPointColor(Color.White)
  9286. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9287. .onChange((checked: boolean) => {
  9288. this.isHightLightCenter = checked;
  9289. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  9290. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  9291. })
  9292. .width(50)
  9293. .height(30)
  9294. .alignSelf(ItemAlign.Start)
  9295. .margin({ left: 12 })
  9296. Blank()
  9297. }
  9298. .width('76%')
  9299. }
  9300. .margin({
  9301. left: 20,
  9302. right: 15,
  9303. top: 10,
  9304. bottom: 10
  9305. })
  9306. }
  9307. Row() {
  9308. Text(`歌词颜色:`)
  9309. .fontSize(14)
  9310. .fontColor(Color.White)
  9311. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9312. .fontSize(15)
  9313. .fontColor(Color.White)
  9314. .margin({ left: 12, right: 12 })
  9315. Column() {
  9316. }
  9317. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9318. .margin({ right: 12 })
  9319. .borderRadius(20)
  9320. .height(28)
  9321. .width(28)
  9322. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9323. Row() {
  9324. SymbolGlyph($r('sys.symbol.paintbrush'))
  9325. .fontColor([Color.White])
  9326. .effectStrategy(1)
  9327. Text(`选择颜色`)
  9328. .fontSize(13)
  9329. .margin({ left: 10 })
  9330. .fontColor(Color.White)
  9331. }
  9332. }
  9333. .backgroundColor(Color.Transparent)
  9334. .border({
  9335. color: '#FFFFFF',
  9336. radius: 20,
  9337. width: 1.8
  9338. })
  9339. .height(36)
  9340. .width(110)
  9341. .onClick(() => {
  9342. this.isShowSelectColor = !this.isShowSelectColor
  9343. })
  9344. .bindPopup(this.isShowSelectColor, {
  9345. builder: this.SelectColor(false, isPip),
  9346. placement: Placement.Top,
  9347. mask: { color: '#33000000' },
  9348. enableArrow: false, //是否显示箭头
  9349. showInSubWindow: false,
  9350. onStateChange: (e) => {
  9351. if (!e.isVisible) {
  9352. this.isShowSelectColor = false
  9353. }
  9354. }
  9355. })
  9356. }
  9357. .width('76%')
  9358. .margin({
  9359. top: 10,
  9360. bottom: 10,
  9361. right: 45,
  9362. left: 20
  9363. })
  9364. Row() {
  9365. Text(`高亮颜色:`)
  9366. .fontSize(14)
  9367. .fontColor(Color.White)
  9368. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  9369. .fontSize(15)
  9370. .fontColor(Color.White)
  9371. .margin({ left: 12, right: 12 })
  9372. Column() {
  9373. }
  9374. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  9375. .margin({ right: 12 })
  9376. .borderRadius(20)
  9377. .height(28)
  9378. .width(28)
  9379. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9380. Row() {
  9381. SymbolGlyph($r('sys.symbol.paintbrush'))
  9382. .fontColor([Color.White])
  9383. .effectStrategy(1)
  9384. Text(`选择颜色`)
  9385. .fontSize(13)
  9386. .margin({ left: 10 })
  9387. .fontColor(Color.White)
  9388. }
  9389. }
  9390. .backgroundColor(Color.Transparent)
  9391. .border({
  9392. color: '#FFFFFF',
  9393. radius: 20,
  9394. width: 1.8
  9395. })
  9396. .height(36)
  9397. .width(110)
  9398. .onClick(() => {
  9399. this.isShowHLSelectColor = !this.isShowHLSelectColor
  9400. })
  9401. .bindPopup(this.isShowHLSelectColor, {
  9402. builder: this.SelectColor(true, isPip),
  9403. placement: Placement.Top,
  9404. mask: { color: '#33000000' },
  9405. enableArrow: false, //是否显示箭头
  9406. showInSubWindow: false,
  9407. onStateChange: (e) => {
  9408. if (!e.isVisible) {
  9409. this.isShowHLSelectColor = false
  9410. }
  9411. }
  9412. })
  9413. }
  9414. .width('76%')
  9415. .margin({
  9416. top: 10,
  9417. bottom: 10,
  9418. right: 45,
  9419. left: 20
  9420. })
  9421. if (isPip) {
  9422. Row() {
  9423. Text(`显示宽度:`)
  9424. .fontSize(14)
  9425. .fontColor(Color.White)
  9426. Slider({
  9427. value: this.pipLyWidth,
  9428. min: 10,
  9429. max: 800,
  9430. step: 1,
  9431. style: SliderStyle.OutSet
  9432. })
  9433. .blockColor(this.themeColor)
  9434. .trackColor($r('app.color.speed_text_color'))
  9435. .selectedColor(Color.White)
  9436. .trackThickness(6)
  9437. .onChange((value: number) => {
  9438. this.pipLyWidth = value
  9439. if (this.pipController) {
  9440. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9441. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  9442. }
  9443. })
  9444. .width('76%')
  9445. }
  9446. .margin({
  9447. left: 20,
  9448. right: 15,
  9449. top: 5,
  9450. bottom: 5
  9451. })
  9452. Row() {
  9453. Text(`显示高度:`)
  9454. .fontSize(14)
  9455. .fontColor(Color.White)
  9456. Slider({
  9457. value: this.pipLyHeight,
  9458. min: 10,
  9459. max: 1000,
  9460. step: 1,
  9461. style: SliderStyle.OutSet
  9462. })
  9463. .blockColor(this.themeColor)
  9464. .trackColor($r('app.color.speed_text_color'))
  9465. .selectedColor(Color.White)
  9466. .trackThickness(6)
  9467. .onChange((value: number) => {
  9468. this.pipLyHeight = value
  9469. if (this.pipController) {
  9470. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9471. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  9472. }
  9473. })
  9474. .width('76%')
  9475. }
  9476. .margin({
  9477. left: 20,
  9478. right: 15,
  9479. top: 5,
  9480. bottom: 5
  9481. })
  9482. }
  9483. Row() {
  9484. Text(`歌词字号:`)
  9485. .fontSize(14)
  9486. .fontColor(Color.White)
  9487. Slider({
  9488. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  9489. min: 12,
  9490. max: 30,
  9491. step: 0.1,
  9492. style: SliderStyle.OutSet
  9493. })
  9494. .blockColor(this.themeColor)
  9495. .trackColor($r('app.color.speed_text_color'))
  9496. .selectedColor(Color.White)
  9497. .trackThickness(6)
  9498. .onChange((value: number) => {
  9499. this.setLyricTextSize(value, isPip)
  9500. })
  9501. .width('76%')
  9502. }
  9503. .margin({
  9504. left: 20,
  9505. right: 15,
  9506. top: 5,
  9507. bottom: 5
  9508. })
  9509. Row() {
  9510. Text(`高亮倍数:`)
  9511. .fontSize(14)
  9512. .fontColor(Color.White)
  9513. Slider({
  9514. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  9515. min: 1,
  9516. max: 2,
  9517. step: 0.1,
  9518. style: SliderStyle.OutSet
  9519. })
  9520. .blockColor(this.themeColor)
  9521. .trackColor($r('app.color.speed_text_color'))
  9522. .selectedColor(Color.White)
  9523. .trackThickness(6)
  9524. .onChange((value: number) => {
  9525. this.setHighLyricTextSize(value, isPip)
  9526. })
  9527. .width('76%')
  9528. }
  9529. .margin({
  9530. left: 20,
  9531. right: 15,
  9532. top: 5,
  9533. bottom: 5
  9534. })
  9535. Row() {
  9536. Text(`歌词间隙:`)
  9537. .fontSize(14)
  9538. .fontColor(Color.White)
  9539. Slider({
  9540. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  9541. min: 0,
  9542. max: 100,
  9543. step: 1,
  9544. style: SliderStyle.OutSet
  9545. })
  9546. .blockColor(this.themeColor)
  9547. .trackColor($r('app.color.speed_text_color'))
  9548. .selectedColor(Color.White)
  9549. .trackThickness(6)
  9550. .onChange((value: number) => {
  9551. this.setLyricLineSpace(value, isPip)
  9552. })
  9553. .width('76%')
  9554. }
  9555. .margin({
  9556. left: 20,
  9557. right: 15,
  9558. top: 5,
  9559. bottom: 5
  9560. })
  9561. //取值间隔为100,默认为400,取值越大,字体越粗
  9562. Row() {
  9563. Text(`歌词字重:`)
  9564. .fontSize(14)
  9565. .fontColor(Color.White)
  9566. Slider({
  9567. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  9568. min: 100,
  9569. max: 900,
  9570. step: 100,
  9571. style: SliderStyle.OutSet
  9572. })
  9573. .blockColor(this.themeColor)
  9574. .trackColor($r('app.color.speed_text_color'))
  9575. .selectedColor(Color.White)
  9576. .trackThickness(6)
  9577. .onChange((value: number) => {
  9578. if (isPip) {
  9579. this.lyricTextWeightPip = value
  9580. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9581. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  9582. } else {
  9583. this.lyricTextWeight = value
  9584. this.lyricController.setTextWeight(this.lyricTextWeight)
  9585. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  9586. }
  9587. })
  9588. .width('76%')
  9589. }
  9590. .margin({
  9591. left: 20,
  9592. right: 15,
  9593. top: 5,
  9594. bottom: 5
  9595. })
  9596. if (!isPip) {
  9597. Row() {
  9598. Text(`歌词模糊:`)
  9599. .fontSize(14)
  9600. .fontColor(Color.White)
  9601. Slider({
  9602. value: isPip ? this.blurDegreePip : this.blurDegree,
  9603. min: 0,
  9604. max: 5,
  9605. step: 0.1,
  9606. style: SliderStyle.OutSet
  9607. })
  9608. .blockColor(this.themeColor)
  9609. .trackColor($r('app.color.speed_text_color'))
  9610. .selectedColor(Color.White)
  9611. .trackThickness(6)
  9612. .onChange((value: number) => {
  9613. this.setBlurDegree(value, isPip)
  9614. })
  9615. .width('76%')
  9616. }
  9617. .margin({
  9618. left: 20,
  9619. right: 15,
  9620. top: 5,
  9621. bottom: 15
  9622. })
  9623. }
  9624. Row() {
  9625. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  9626. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  9627. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  9628. }
  9629. .justifyContent(FlexAlign.Center)
  9630. .margin({ top: 3, bottom: 10 })
  9631. }
  9632. }
  9633. private setBlurDegree(index: number, isPip: boolean) {
  9634. if (isPip) {
  9635. this.blurDegreePip = index
  9636. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  9637. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  9638. } else {
  9639. this.blurDegree = index
  9640. this.lyricController.setBlurDegree(this.blurDegree)
  9641. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  9642. }
  9643. }
  9644. private setLyricAlignMode(index: number, isPip: boolean) {
  9645. if (isPip) {
  9646. this.currentLyricAlignModePip = index
  9647. if (this.currentLyricAlignModePip === 1) {
  9648. this.lyricControllerXF.setAlignMode("left")
  9649. } else {
  9650. this.lyricControllerXF.setAlignMode("center")
  9651. }
  9652. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  9653. } else {
  9654. this.currentLyricAlignMode = index
  9655. if (this.currentLyricAlignMode === 1) {
  9656. this.lyricController.setAlignMode("left")
  9657. } else {
  9658. this.lyricController.setAlignMode("center")
  9659. }
  9660. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  9661. }
  9662. }
  9663. private setLyricTextSize(index: number, isPip: boolean) {
  9664. if (isPip) {
  9665. this.currentLyricSizePip = index
  9666. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  9667. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  9668. } else {
  9669. this.currentLyricSize = index
  9670. this.lyricController.setTextSize(this.currentLyricSize)
  9671. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  9672. }
  9673. }
  9674. private setHighLyricTextSize(scale: number, isPip: boolean) {
  9675. if (isPip) {
  9676. this.currentHightLyricSizePip = scale
  9677. this.lyricControllerXF
  9678. .setHighlightScale(this.currentHightLyricSizePip)
  9679. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  9680. } else {
  9681. this.currentHightLyricSize = scale
  9682. this.lyricController
  9683. .setHighlightScale(this.currentHightLyricSize)
  9684. PreferencesUtil.putSync('HighLyricTextSize', scale)
  9685. }
  9686. }
  9687. private setLyricLineSpace(index: number, isPip: boolean) {
  9688. if (isPip) {
  9689. this.currentLyricLineSpacePip = index
  9690. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  9691. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  9692. } else {
  9693. this.currentLyricLineSpace = index
  9694. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  9695. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  9696. }
  9697. }
  9698. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  9699. LogUtil.info('onecold isBG = ' + isBG)
  9700. if (isBG) { //如果是设置悬浮背景
  9701. this.pipBg = color
  9702. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  9703. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9704. return
  9705. }
  9706. if (isPip) {
  9707. this.currentLyricColorPip = color
  9708. this.lyricControllerXF
  9709. .setTextColor(this.currentLyricColorPip)
  9710. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  9711. } else {
  9712. this.currentLyricColor = color
  9713. this.lyricController
  9714. .setTextColor(this.currentLyricColor)
  9715. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  9716. }
  9717. }
  9718. private changeLyricHightLightColor(color: string, isPip: boolean) {
  9719. if (isPip) {
  9720. this.currentHighLightLyricColorPip = color
  9721. this.lyricControllerXF
  9722. .setHighlightColor(this.currentHighLightLyricColorPip)
  9723. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  9724. } else {
  9725. this.currentHighLightLyricColor = color
  9726. this.lyricController
  9727. .setHighlightColor(this.currentHighLightLyricColor)
  9728. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  9729. }
  9730. }
  9731. // 构建时间控制器
  9732. @Builder
  9733. BuildTimeControls() {
  9734. Column() {
  9735. // 时间显示
  9736. Text(this.getTimeText())
  9737. .fontSize(18)
  9738. .fontColor(Color.White)
  9739. .margin({ bottom: 10 })
  9740. Row() {
  9741. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  9742. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  9743. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  9744. }
  9745. .justifyContent(FlexAlign.Center)
  9746. }
  9747. .margin({ top: 12, bottom: 8 })
  9748. }
  9749. // 精度按钮组件
  9750. @Builder
  9751. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  9752. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9753. Column() {
  9754. Image(icon)
  9755. .width(28)
  9756. .margin({ bottom: 5 })
  9757. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  9758. Text(label)
  9759. .fontSize(12)
  9760. .fontColor('#FFFFFF')
  9761. }
  9762. }
  9763. .backgroundColor(Color.Transparent)
  9764. .enabled(!this.isButtonDisabled(step))
  9765. .onClick(() => this.handlePrecisionAdjust(step))
  9766. .padding(5)
  9767. .width(66)
  9768. .height(66)
  9769. .margin({ left: 18, right: 18 })
  9770. .border({
  9771. color: '#FFFFFF',
  9772. width: 1.8
  9773. })
  9774. }
  9775. private handlePrecisionAdjust(step: number) {
  9776. if (step === 0) {
  9777. this.timeOffset = 0
  9778. return
  9779. }
  9780. // 精度处理:保留1位小数
  9781. const newOffset = Number((this.timeOffset + step).toFixed(5))
  9782. // 边界保护(±15.0秒)
  9783. if (newOffset < -30.0 || newOffset > 30.0) {
  9784. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  9785. return
  9786. }
  9787. // 状态更新
  9788. this.timeOffset = newOffset
  9789. }
  9790. // 按钮禁用逻辑
  9791. private isButtonDisabled(step: number): boolean {
  9792. const futureOffset = this.timeOffset + step
  9793. return (futureOffset < -30.0) || (futureOffset > 30.0)
  9794. }
  9795. // 时间显示文本升级
  9796. private getTimeText(): string {
  9797. const absValue = Math.abs(this.timeOffset)
  9798. return this.timeOffset === 0
  9799. ? '歌词时间已重置'
  9800. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  9801. }
  9802. // 导入 本地歌词 搜索歌词
  9803. @Builder
  9804. pushLyricButton(icon: Resource, step: number, label: string) {
  9805. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9806. Row() {
  9807. Image(icon)
  9808. .width(14)
  9809. .margin({ left: 13 })
  9810. Text(label)
  9811. .fontSize(12)
  9812. .margin({ left: 6 })
  9813. .fontColor('#FFFFFF')
  9814. }
  9815. }
  9816. .onClick(() => {
  9817. switch (step) {
  9818. case 0:
  9819. this.callFilePickerSelectFileForLyric()
  9820. break;
  9821. case 1:
  9822. //判断有没有设置api
  9823. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  9824. this.isLyricSetting = false
  9825. this.showTipsDialog()
  9826. return
  9827. }
  9828. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9829. ToastUtil.showToast('正在获取')
  9830. this.isLyricSetting = false
  9831. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9832. this.initLyric(lyricPath, true);
  9833. }
  9834. break;
  9835. }
  9836. })
  9837. .padding(5)
  9838. .width(110)
  9839. .backgroundColor(Color.Transparent)
  9840. .height(40)
  9841. .margin({ left: 6, right: 6 })
  9842. .border({
  9843. color: '#FFFFFF',
  9844. radius: 20,
  9845. width: 1.8
  9846. })
  9847. }
  9848. showVipDialog() {
  9849. DialogHelper.showCustomContentDialog({
  9850. dialogId: 'vip',
  9851. title: "友情提示",
  9852. autoCancel: false, //点击遮障层时,不关闭弹窗
  9853. backCancel: true, //点击返回键,不关闭弹窗
  9854. contentBuilder: () => {
  9855. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  9856. },
  9857. buttons: [],
  9858. })
  9859. }
  9860. //去赞助的自定义内容
  9861. @Builder
  9862. customVipBuilder(content: string) {
  9863. Column() {
  9864. Text(content)
  9865. .fontColor(Color.Gray)
  9866. .fontSize(16)
  9867. .alignSelf(ItemAlign.Start)
  9868. .margin({ bottom: 15 })
  9869. .fontSize(16)
  9870. Row() {
  9871. Button('取消')
  9872. .fontColor(Color.White)
  9873. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9874. .height(50)
  9875. .layoutWeight(1)
  9876. .stateEffect(true)
  9877. .margin({ right: 6 })
  9878. .onClick(() => {
  9879. DialogHelper.closeDialog('vip'); //关闭弹框
  9880. })
  9881. Button('开通')
  9882. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9883. .layoutWeight(1)
  9884. .height(50)
  9885. .backgroundColor(this.themeColor)
  9886. .stateEffect(true)
  9887. .margin({ left: 6 })
  9888. .onClick(() => {
  9889. DialogHelper.closeDialog('vip'); //关闭弹框
  9890. this.isShowPlay = false
  9891. this.mType = 1 //跳转到用户中心
  9892. // router.pushUrl({
  9893. // url: 'pages/VipPage'
  9894. // }, router.RouterMode.Single);
  9895. })
  9896. }
  9897. }
  9898. .width("100%")
  9899. .padding(10)
  9900. }
  9901. showTipsDialog() {
  9902. DialogHelper.showCustomContentDialog({
  9903. dialogId: 'tips',
  9904. title: "友情提示",
  9905. autoCancel: false, //点击遮障层时,不关闭弹窗
  9906. backCancel: true, //点击返回键,不关闭弹窗
  9907. contentBuilder: () => {
  9908. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  9909. },
  9910. buttons: [],
  9911. })
  9912. }
  9913. @Builder
  9914. customTipsBuilder(content: string) {
  9915. Column() {
  9916. Text(content)
  9917. .fontColor(Color.Gray)
  9918. .fontSize(16)
  9919. .alignSelf(ItemAlign.Start)
  9920. .margin({ bottom: 15 })
  9921. .fontSize(16)
  9922. Row() {
  9923. Button('取消')
  9924. .fontColor(Color.White)
  9925. .backgroundColor(this.themeColor)
  9926. .height(50)
  9927. .layoutWeight(1)
  9928. .stateEffect(true)
  9929. .margin({ right: 6 })
  9930. .onClick(() => {
  9931. DialogHelper.closeDialog('tips'); //关闭弹框
  9932. })
  9933. Button('跳转')
  9934. .fontColor(Color.White)//
  9935. .layoutWeight(1)
  9936. .height(50)
  9937. .backgroundColor(this.themeColor)
  9938. .stateEffect(true)
  9939. .margin({ left: 6 })
  9940. .onClick(() => {
  9941. DialogHelper.closeDialog('tips'); //关闭弹框
  9942. this.isShowEdit = false
  9943. this.longItemFilePath = ''
  9944. // if(this.isGridMusic&&!this.isShowPlay){
  9945. // this.longItemFilePath== ''
  9946. // }else{
  9947. // this.isShowEdit = false
  9948. // }
  9949. this.isShowMoreView = false;
  9950. this.isShowPlay = false
  9951. this.mType = 4
  9952. // router.pushUrl({
  9953. // url: 'pages/SettingPage'
  9954. // }, router.RouterMode.Single);
  9955. })
  9956. }
  9957. }
  9958. .width("100%")
  9959. .padding(10)
  9960. }
  9961. @Builder
  9962. PlayMoreSheet() {
  9963. Column() {
  9964. this.MoreList()
  9965. }
  9966. .width('100%')
  9967. .height('100%')
  9968. }
  9969. @Builder
  9970. MoreList() {
  9971. Scroll() {
  9972. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9973. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  9974. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9975. Row() {
  9976. if (more.id === 3&&this.currentSong) {
  9977. Image(more.image)
  9978. .width(24)
  9979. .height(24)
  9980. .margin({ left: 10, right: 10 })
  9981. Text(more.title)
  9982. .fontSize(16)
  9983. .fontColor(Color.White)
  9984. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  9985. height: this.isCoverOpacity() ? '95%' : '95%',
  9986. dragBar: true,
  9987. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9988. showClose: true,
  9989. blurStyle: BlurStyle.Thin,
  9990. backgroundColor: Color.Transparent,
  9991. title: { title: '歌曲信息' }
  9992. })
  9993. } else if (more.id === 15 && this.currentSong) { //编辑标签
  9994. Image(more.image)
  9995. .width(24)
  9996. .height(24)
  9997. .margin({ left: 10, right: 10 })
  9998. Text(more.title)
  9999. .fontSize(16)
  10000. .fontColor(Color.White)
  10001. } else if (more.id === 5) { //定时关闭
  10002. Image(more.image)
  10003. .width(24)
  10004. .height(24)
  10005. .margin({ left: 10, right: 10 })
  10006. Text(more.title)
  10007. .fontSize(16)
  10008. .fontColor(Color.White)
  10009. .onClick(() => {
  10010. this.doMore(more.id)
  10011. })
  10012. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  10013. height: this.isCoverOpacity() ? '95%' : '95%',
  10014. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10015. dragBar: true,
  10016. showClose: true,
  10017. title: { title: $r('app.string.time_close') }
  10018. })
  10019. } else if (more.id === 2) { //歌词设置
  10020. Image(more.image)
  10021. .width(24)
  10022. .height(24)
  10023. .margin({ left: 10, right: 10 })
  10024. Text(more.title)
  10025. .fontSize(16)
  10026. .fontColor(Color.White)
  10027. } else if (more.id === 16) { //悬浮歌词设置
  10028. Image(more.image)
  10029. .width(24)
  10030. .height(24)
  10031. .margin({ left: 10, right: 10 })
  10032. Text(more.title)
  10033. .fontSize(16)
  10034. .fontColor(Color.White)
  10035. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  10036. height: this.isCoverOpacity() ? '95%' : '95%',
  10037. dragBar: true,
  10038. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10039. showClose: true,
  10040. blurStyle: BlurStyle.Thin,
  10041. backgroundColor: Color.Transparent,
  10042. title: { title: '悬浮歌词' }
  10043. })
  10044. } else if (more.id === 11) {
  10045. Image(more.image)
  10046. .width(24)
  10047. .height(24)
  10048. .margin({ left: 10, right: 10 })
  10049. Text(more.title)
  10050. .fontSize(16)
  10051. .fontColor(Color.White)
  10052. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  10053. height: this.isCoverOpacity() ? '95%' : '60%',
  10054. dragBar: true,
  10055. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10056. showClose: true,
  10057. blurStyle: BlurStyle.Thin,
  10058. backgroundColor: Color.Transparent,
  10059. title: { title: '跳过头尾' }
  10060. })
  10061. } else if (more.id === 12) { //投播
  10062. AVCastPicker({
  10063. customPicker: (): void => this.TPImageBuilder(more),
  10064. onStateChange: (state) => {
  10065. if (state == AVCastPickerState.STATE_APPEARING) {
  10066. console.log(' The picker starts showing.');
  10067. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10068. console.log(' The picker finishes presenting.');
  10069. }
  10070. },
  10071. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  10072. sessionType: 'video'
  10073. })
  10074. .id('AVCastPicker')
  10075. } else {
  10076. Image(more.image)
  10077. .width(24)
  10078. .height(24)
  10079. .fillColor(Color.White)
  10080. .margin({ left: 10, right: 10 })
  10081. .onClick(() => {
  10082. this.doMore(more.id)
  10083. })
  10084. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  10085. .fontSize(16)
  10086. .fontColor(Color.White)
  10087. .onClick(() => {
  10088. this.doMore(more.id)
  10089. })
  10090. Select([//倍速
  10091. { value: '0.25x' },
  10092. { value: '0.5x' },
  10093. { value: '0.75x' },
  10094. { value: '1x' },
  10095. { value: '1.25x' },
  10096. { value: '1.5x' },
  10097. { value: '1.75x' },
  10098. { value: '2x' },
  10099. { value: '3x' }])
  10100. .font({ size: 16, weight: FontWeight.Medium })
  10101. .fontColor($r('sys.color.white'))
  10102. .margin({ left: 25 })
  10103. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  10104. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  10105. .value(Utility.optimizedFormat(this.playSpeed))
  10106. .onSelect(async (_index: number, text?: string | undefined) => {
  10107. let speed = parseFloat(text?.replace('x', '') || '1');
  10108. if (!CommonConstants.video_speed_list.includes(speed)) {
  10109. speed = 1;
  10110. }
  10111. this.playSpeed = speed
  10112. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10113. })
  10114. Slider({
  10115. value: this.volume,
  10116. min: 0,
  10117. max: 1,
  10118. step: 0.1,
  10119. style: SliderStyle.OutSet
  10120. })
  10121. .margin({ left: 18, right: 8 })
  10122. .blockColor(this.themeColor)
  10123. .trackColor($r('app.color.speed_text_color'))
  10124. .selectedColor(Color.White)
  10125. .trackThickness(9)
  10126. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  10127. .onChange((value: number) => {
  10128. this.volume = value;
  10129. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10130. PreferencesUtil.putSync('DefalutVolume',this.volume)
  10131. })
  10132. .layoutWeight(1)
  10133. Blank()
  10134. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  10135. .selectedColor(this.themeColor)
  10136. .switchPointColor(Color.White)
  10137. .margin({ right: 15 })
  10138. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10139. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  10140. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10141. if (more.id == 6) {
  10142. this.isMusicMemoryPlay = checked;
  10143. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  10144. if (this.isMusicMemoryPlay) {
  10145. ToastUtil.showToast('记忆播放已开启')
  10146. } else {
  10147. ToastUtil.showToast('记忆播放已关闭')
  10148. }
  10149. }
  10150. })
  10151. .width(48)
  10152. .height(24);
  10153. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  10154. .selectedColor(this.themeColor)
  10155. .switchPointColor(Color.White)
  10156. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10157. .margin({ right: 15 })
  10158. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  10159. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10160. if (more.id == 7) {
  10161. this.isMusicBGCover = checked;
  10162. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  10163. if (this.isMusicBGCover) {
  10164. ToastUtil.showToast('播放背景随音乐封面已开启')
  10165. } else {
  10166. ToastUtil.showToast('播放背景随音乐封面已关闭')
  10167. }
  10168. }
  10169. })
  10170. .width(48)
  10171. .height(24);
  10172. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  10173. .selectedColor(this.themeColor)
  10174. .switchPointColor(Color.White)
  10175. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10176. .margin({ right: 15 })
  10177. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  10178. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10179. if (more.id == 8) {
  10180. this.isSavePlayMode = checked;
  10181. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  10182. if (this.isSavePlayMode) {
  10183. ToastUtil.showToast('保存播放模式已开启')
  10184. } else {
  10185. ToastUtil.showToast('保存播放模式已关闭')
  10186. }
  10187. }
  10188. })
  10189. .width(48)
  10190. .height(24);
  10191. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  10192. .selectedColor(this.themeColor)
  10193. .switchPointColor(Color.White)
  10194. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10195. .margin({ right: 15 })
  10196. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  10197. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10198. if (more.id == 13) {
  10199. this.isCoverRectangle = checked;
  10200. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  10201. if (this.isCoverRectangle) {
  10202. ToastUtil.showToast('封面方形已开启')
  10203. this.animationRoFun()
  10204. } else {
  10205. ToastUtil.showToast('封面圆形已开启')
  10206. this.animationRoFun()
  10207. }
  10208. }
  10209. })
  10210. .width(48)
  10211. .height(24);
  10212. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  10213. .selectedColor(this.themeColor)
  10214. .switchPointColor(Color.White)
  10215. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10216. .margin({ right: 15 })
  10217. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  10218. .onChange((checked: boolean) => { // 是否开启背景流光效果
  10219. if (more.id == 21) {
  10220. this.isShowBgLiuGUANG = checked;
  10221. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  10222. }
  10223. })
  10224. .width(48)
  10225. .height(24);
  10226. }
  10227. }
  10228. .width('100%')
  10229. .height(45)
  10230. .padding(15)
  10231. .backgroundColor(Color.Transparent)
  10232. .borderRadius(12)
  10233. .margin({ bottom: 6 })
  10234. }
  10235. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  10236. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10237. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  10238. .backgroundColor(Color.Transparent)
  10239. .onClick(() => {
  10240. this.doMore(more.id)
  10241. })
  10242. });
  10243. }
  10244. .width('100%')
  10245. .padding(16)
  10246. }.margin({ bottom: 18 })
  10247. }
  10248. @Builder
  10249. TPImageBuilder(more: MoreItem): void {
  10250. Row() {
  10251. Image($r('app.media.tuoping'))
  10252. .width(22)
  10253. .height(22)
  10254. .margin({ left: 10, right: 10 })
  10255. Text(more.title)
  10256. .fontSize(16)
  10257. .fontColor(Color.White)
  10258. }
  10259. .width('100%')
  10260. .layoutWeight(1)
  10261. .alignItems(VerticalAlign.Center)
  10262. .justifyContent(FlexAlign.Start)
  10263. }
  10264. private moreItems: MoreItem[] = [
  10265. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  10266. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  10267. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  10268. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  10269. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  10270. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  10271. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  10272. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  10273. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  10274. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  10275. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  10276. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  10277. { id: 4, image: $r('app.media.share2'), title: '分享' },
  10278. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  10279. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  10280. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  10281. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  10282. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  10283. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  10284. ];
  10285. @State isShowBgLiuGUANG: boolean = true;
  10286. @State isShowMoreView: boolean = false;
  10287. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  10288. @State isShowTimeCloseMore: boolean = false
  10289. @State isShowDetailMore: boolean = false
  10290. @State isMusicBGCover: boolean = true
  10291. @State isSavePlayMode: boolean = true
  10292. @State isLyricSetting: boolean = false
  10293. @State isJumpSetting: boolean = false
  10294. @State isShowEdit: boolean = false
  10295. @State showPipLyric: boolean = false
  10296. async setRingTone() {
  10297. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  10298. return
  10299. }
  10300. // 确定后的逻辑
  10301. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  10302. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  10303. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  10304. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  10305. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  10306. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  10307. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  10308. , this.videoUrl, this.name).then(res => {
  10309. LogUtil.info('onecold setFlag :' + res);
  10310. });
  10311. }
  10312. doMore(moreId: number) {
  10313. switch (moreId) {
  10314. case 2: //歌词
  10315. this.isLyricSetting = !this.isLyricSetting;
  10316. this.isShowMoreView = false
  10317. break;
  10318. case 3: //详情
  10319. this.isShowDetailMore = !this.isShowDetailMore;
  10320. break;
  10321. case 4: //分享
  10322. if (this.currentSong !== undefined) {
  10323. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  10324. }
  10325. this.isShowMoreView = false
  10326. break;
  10327. case 5: //定时关闭
  10328. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  10329. break;
  10330. case 10: //设为铃声
  10331. this.setRingTone()
  10332. this.isShowMoreView = false
  10333. break;
  10334. case 11: //跳过头尾
  10335. this.isJumpSetting = !this.isJumpSetting;
  10336. break;
  10337. case 13: //倍速
  10338. break;
  10339. case 14: //搜索封面
  10340. if (this.currentSong !== undefined) {
  10341. this.doSearchCover(this.currentSong)
  10342. }
  10343. this.isShowMoreView = false
  10344. break;
  10345. case 15: //编辑标签
  10346. this.setEditStrEmpty()
  10347. this.tempLyricContent = this.lyricContent
  10348. this.isShowEdit = !this.isShowEdit;
  10349. break;
  10350. case 16: //悬浮歌词
  10351. this.showPipLyric = !this.showPipLyric;
  10352. break;
  10353. case 17: //横屏模式
  10354. if (this.isLandscape) {
  10355. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  10356. } else {
  10357. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  10358. }
  10359. this.isShowMoreView = false
  10360. break;
  10361. case 20://AB循环
  10362. this.isABSheet = !this.isABSheet
  10363. break;
  10364. }
  10365. }
  10366. //AB循环
  10367. @State isOpenAB:boolean = false
  10368. @State jumpATime:number = 0
  10369. @State jumpBTime:number = 0
  10370. @State isABSheet:boolean = false
  10371. @Builder
  10372. ABLoopSheet() {
  10373. ABLoopComptent({
  10374. jumpATime:this.jumpATime,
  10375. jumpBTime:this.jumpBTime,
  10376. onClickAItem: async ()=>{
  10377. if(this.mIjkMediaPlayer){
  10378. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  10379. }
  10380. },
  10381. onClickBItem: async ()=>{
  10382. if(this.mIjkMediaPlayer){
  10383. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  10384. if(this.jumpBTime<=this.jumpATime){
  10385. ToastUtil.showToast('设置B点时间不能小于A点时间')
  10386. this.jumpBTime = 0
  10387. }
  10388. }
  10389. },
  10390. onCancleButtonClick: async ()=>{
  10391. this.isOpenAB = false
  10392. this.isABSheet = false
  10393. },
  10394. onStartButtonClick: async ()=>{
  10395. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  10396. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  10397. return
  10398. }
  10399. this.isABSheet = false
  10400. this.startABLoop()
  10401. },
  10402. })
  10403. }
  10404. //开始AB循环
  10405. startABLoop(){
  10406. if(this.mIjkMediaPlayer){
  10407. this.seekTo(this.jumpATime+'')
  10408. this.isOpenAB = true
  10409. }
  10410. }
  10411. /**
  10412. * 切换横竖屏
  10413. *
  10414. */
  10415. setOrientation(orientation: number) {
  10416. this.windowClass.setPreferredOrientation(orientation).then(() => {
  10417. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  10418. }).catch((err: BusinessError) => {
  10419. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  10420. });
  10421. }
  10422. /**
  10423. * 画中画功能(悬浮歌词功能)
  10424. *
  10425. */
  10426. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  10427. pipController?: PiPWindow.PiPController;
  10428. navigationId: string = '';
  10429. @State curState: string = '';
  10430. @State curError: ResourceStr = '';
  10431. @State pipBg: string = '#E8E8E8'
  10432. @State buttonAction: string = '';
  10433. //开启画中画功能
  10434. async startPip() {
  10435. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  10436. if (!this.pipController) {
  10437. await this.createPipController();
  10438. }
  10439. if (!this.pipController) {
  10440. Logger.info(`[${TAG}] pipController create error`);
  10441. return;
  10442. }
  10443. await this.pipController.startPiP();
  10444. }
  10445. async stopPip() {
  10446. if (!this.pipController) {
  10447. Logger.info(`[${TAG}] pipController is not exist`);
  10448. return;
  10449. }
  10450. this.isOpenPip = false
  10451. await this.pipController.stopPiP();
  10452. }
  10453. async createPipController() {
  10454. this.pipController = await PiPWindow.create({
  10455. context: getContext(this),
  10456. componentController: this.xcomponentController,
  10457. navigationId: this.navigationId,
  10458. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  10459. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  10460. customUIController: this.nodeController,
  10461. });
  10462. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  10463. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  10464. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10465. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  10466. this.onStateChange(state, reason);
  10467. });
  10468. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  10469. this.onActionEvent(event, status);
  10470. });
  10471. }
  10472. destroyPipController() {
  10473. if (!this.pipController) {
  10474. return;
  10475. }
  10476. this.pipController.off('stateChange');
  10477. this.pipController.off('controlPanelActionEvent');
  10478. this.pipController = undefined;
  10479. }
  10480. onStateChange(state: PiPWindow.PiPState, reason: string) {
  10481. switch (state) {
  10482. case PiPWindow.PiPState.ABOUT_TO_START:
  10483. this.curState = 'ABOUT_TO_START';
  10484. this.curError = $r('app.string.current_error_hint');
  10485. break;
  10486. case PiPWindow.PiPState.STARTED:
  10487. this.curState = 'STARTED';
  10488. this.curError = $r('app.string.current_error_hint');
  10489. break;
  10490. case PiPWindow.PiPState.ABOUT_TO_STOP:
  10491. this.curState = 'ABOUT_TO_STOP';
  10492. this.curError = $r('app.string.current_error_hint');
  10493. break;
  10494. case PiPWindow.PiPState.STOPPED:
  10495. this.curState = 'STOPPED';
  10496. this.curError = $r('app.string.current_error_hint');
  10497. this.stopPip()
  10498. this.destroyPipController()
  10499. break;
  10500. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  10501. this.curState = 'ABOUT_TO_RESTORE';
  10502. this.curError = $r('app.string.current_error_hint');
  10503. break;
  10504. case PiPWindow.PiPState.ERROR:
  10505. this.curState = 'ERROR';
  10506. this.curError = reason;
  10507. break;
  10508. default:
  10509. break;
  10510. }
  10511. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  10512. }
  10513. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  10514. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  10515. switch (event) {
  10516. case 'playbackStateChanged':
  10517. if (status === 0) {
  10518. this.pause();
  10519. } else {
  10520. console.info('onecold startPlayOrResumePlay 9869')
  10521. this.startPlayOrResumePlay();
  10522. }
  10523. break;
  10524. case 'nextVideo':
  10525. // 切换到下一个视频
  10526. this.playNext().catch(() => {
  10527. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  10528. });
  10529. break;
  10530. case 'previousVideo':
  10531. // 切换到上一个视频
  10532. this.playPrevious().catch(() => {
  10533. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  10534. });
  10535. break;
  10536. case 'previousVideo':
  10537. // 切换到上一个视频
  10538. this.playPrevious().catch(() => {
  10539. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  10540. });
  10541. break;
  10542. default:
  10543. }
  10544. this.buttonAction = event + `-status:${status}`;
  10545. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  10546. }
  10547. /**
  10548. * 画中画功能(悬浮歌词功能)结束
  10549. *
  10550. */
  10551. async doSearchCover(item: VideoItem): Promise<string> {
  10552. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  10553. this.isShowMoreView = false;
  10554. this.showTipsDialog();
  10555. return ''; // Return empty string when no API is configured
  10556. }
  10557. if (!item) {
  10558. return ''; // Return empty string if item is undefined
  10559. }
  10560. const artist = item?.artist || ''; // Use empty string if artist is missing
  10561. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  10562. }
  10563. /**
  10564. *api搜索封面
  10565. *item,根据title和artist
  10566. */
  10567. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  10568. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  10569. LogUtil.debug("onecold res =" + res);
  10570. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10571. if (item.filePath == this.currentSong?.filePath) {
  10572. this.cover = res;
  10573. if (this.currentSong) {
  10574. this.currentSong.pixelMapPath = res;
  10575. }
  10576. }
  10577. // Update pixel map path but always return res regardless of success
  10578. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  10579. if (success) {
  10580. this.doUpdateData();
  10581. console.log("onecold 更新音乐封面成功,数据库已同步");
  10582. } else {
  10583. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  10584. }
  10585. // Note: We don't resolve/reject here because we already returned res
  10586. });
  10587. LogUtil.debug("onecold this.cover =" + this.cover);
  10588. }
  10589. return res; // Always return res regardless of updatePixelMapPath result
  10590. });
  10591. }
  10592. @State jumpTopTime: number = 0
  10593. @State jumpEndTime: number = 0
  10594. @State isOpenJump: boolean = false
  10595. @Builder
  10596. JumpTopEndSheet() {
  10597. Scroll() {
  10598. Column() {
  10599. Column() {
  10600. Text('仅对本播放列表有效')
  10601. .fontSize(16)
  10602. .fontColor($r('app.color.text_color'))
  10603. // 跳过头尾
  10604. Column() {
  10605. Row() {
  10606. Text('跳过片头:')
  10607. .fontSize(16)
  10608. .fontColor($r('app.color.text_color'))
  10609. Text(this.jumpTopTime + 's')
  10610. .fontSize(16)
  10611. .fontColor($r('app.color.text_color'))
  10612. }
  10613. .margin({ bottom: 5 })
  10614. Row() {
  10615. Slider({
  10616. value: this.jumpTopTime,
  10617. min: 0,
  10618. max: 120,
  10619. step: 1,
  10620. style: SliderStyle.OutSet
  10621. })
  10622. .blockColor(this.themeColor)
  10623. .trackColor($r('app.color.speed_text_color'))
  10624. .selectedColor(Color.White)
  10625. .trackThickness(8)
  10626. .onChange((value: number) => {
  10627. this.jumpTopTime = value;
  10628. })
  10629. .width('85%')
  10630. }
  10631. .alignItems(VerticalAlign.Top)
  10632. }
  10633. .margin({ top: 10, bottom: 10 })
  10634. // 跳过头尾
  10635. Column() {
  10636. Row() {
  10637. Text('跳过片尾:')
  10638. .fontSize(16)
  10639. .fontColor($r('app.color.text_color'))
  10640. Text(this.jumpEndTime + 's')
  10641. .fontSize(16)
  10642. .fontColor($r('app.color.text_color'))
  10643. }
  10644. .margin({ bottom: 5 })
  10645. Row() {
  10646. Slider({
  10647. value: this.jumpEndTime,
  10648. min: 0,
  10649. max: 120,
  10650. step: 1,
  10651. style: SliderStyle.OutSet
  10652. })
  10653. .blockColor(this.themeColor)
  10654. .trackColor($r('app.color.speed_text_color'))
  10655. .selectedColor(Color.White)
  10656. .trackThickness(8)
  10657. .onChange((value: number) => {
  10658. this.jumpEndTime = value;
  10659. })
  10660. .width('85%')
  10661. }
  10662. .alignItems(VerticalAlign.Top)
  10663. }
  10664. .margin({ top: 10, bottom: 10 })
  10665. Row() {
  10666. Button('保存设置')
  10667. .fontColor(Color.White)
  10668. .layoutWeight(1)
  10669. .height(40)
  10670. .width(80)
  10671. .backgroundColor(this.themeColor)
  10672. .stateEffect(true)
  10673. .margin({ left: 0, bottom: 20 })
  10674. .onClick(async () => {
  10675. if (!Utility.isNoble()) {
  10676. this.isJumpSetting = false
  10677. this.isShowMoreView = false
  10678. this.showVipDialog()
  10679. return
  10680. }
  10681. if (this.currentSong === undefined) {
  10682. return
  10683. }
  10684. if (this.modeType === 0) {
  10685. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10686. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  10687. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  10688. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  10689. } else if (this.modeType === 1) { //媒体库
  10690. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  10691. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  10692. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  10693. } else if (this.modeType === 2) { //艺术家
  10694. if (this.currentSong?.artist) {
  10695. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  10696. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  10697. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  10698. }
  10699. } else if (this.modeType === 3) { //专辑
  10700. if (this.currentSong?.album) {
  10701. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  10702. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  10703. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  10704. }
  10705. }
  10706. ToastUtil.showShort("保存成功")
  10707. this.isJumpSetting = false
  10708. })
  10709. }
  10710. .margin({
  10711. left: 38,
  10712. right: 38,
  10713. top: 10,
  10714. bottom: 10
  10715. })
  10716. .width(120)
  10717. .height(50)
  10718. }
  10719. }
  10720. }
  10721. .width('100%')
  10722. .height('100%')
  10723. }
  10724. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  10725. private onStateVastChange(state: AVCastPickerState) {
  10726. if (state == AVCastPickerState.STATE_APPEARING) {
  10727. console.log('The picker starts showing.');
  10728. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10729. console.log('The picker finishes presenting.');
  10730. }
  10731. }
  10732. private showSelectLyric() {
  10733. DialogHelper.showActionSheetDialog({
  10734. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  10735. // sheets: ["本地歌词", "搜索歌词"],
  10736. sheets: [
  10737. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  10738. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  10739. ],
  10740. maskColor: Color.Transparent,
  10741. backgroundColor: $r('app.color.bg_card'),
  10742. transition: AnimationHelper.transitionInDown(666),
  10743. onAction: (index) => {
  10744. switch (index) {
  10745. case 0:
  10746. this.callFilePickerSelectFileForLyric()
  10747. break;
  10748. case 1:
  10749. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10750. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10751. this.initLyric(lyricPath);
  10752. }
  10753. break;
  10754. }
  10755. }
  10756. })
  10757. }
  10758. // 拉起picker选择文件管理器
  10759. async callFilePickerSelectFileForLyric(): Promise<void> {
  10760. try {
  10761. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  10762. DocumentSelectOptions.maxSelectNumber = 1
  10763. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  10764. let documentPicker = new picker.DocumentViewPicker();
  10765. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  10766. Logger.info(TAG,
  10767. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  10768. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  10769. this.saveVideoDatasLyric(DocumentSelectResult)
  10770. }
  10771. }).catch((err: BusinessError) => {
  10772. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  10773. });
  10774. } catch (err) {
  10775. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  10776. }
  10777. }
  10778. async saveVideoDatasLyric(uris: string[]) {
  10779. if (ArrayUtil.isEmpty(uris)) {
  10780. return
  10781. }
  10782. let newUris: string[] = [];
  10783. for (let i = 0; i < uris.length; i++) {
  10784. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  10785. Logger.info(TAG, 'filePath uri: ' + filePath);
  10786. newUris.push(filePath)
  10787. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  10788. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  10789. fileIo.copyFileSync(file.fd, file2.fd)
  10790. fileIo.closeSync(file);
  10791. fileIo.closeSync(file2);
  10792. this.initLyric(filePath,false,false,true)
  10793. }
  10794. }
  10795. private initDelayPlay(context: object) {
  10796. this.mContext = context;
  10797. }
  10798. startPipLyric() {
  10799. if (this.pipController) {
  10800. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10801. PiPWindow.PiPControlStatus.PLAY);
  10802. }
  10803. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  10804. if (this.isOpenPip) {
  10805. this.startPip()
  10806. } else {
  10807. this.stopPip()
  10808. }
  10809. }
  10810. //startOffset 从cue分轨时间开始播
  10811. private startPlayOrResumePlay(startOffset?:number) {
  10812. //针对dsf文件高采样率sampleRate>441000,统一转wav播放
  10813. const sampleRate = this.currentSong?.sampleRate||0
  10814. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  10815. console.info('onecold 采样率 ='+sampleRate)
  10816. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  10817. console.info('onecold newDsfPath ='+newDsfPath)
  10818. if(!FileUtil.accessSync(newDsfPath)){
  10819. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  10820. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  10821. this.videoUrl = newDsfPath
  10822. this.startPlay(startOffset)
  10823. }).catch((e:object)=>{
  10824. console.info("task1 catch e: " + e);
  10825. })
  10826. }else{
  10827. this.videoUrl = newDsfPath
  10828. this.startPlay(startOffset)
  10829. }
  10830. }else{
  10831. this.startPlay(startOffset)
  10832. }
  10833. }
  10834. startPlay(startOffset?:number) {
  10835. this.startPipLyric()
  10836. this.mDestroyPage = false;
  10837. this.animationState = AnimationStatus.Running
  10838. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  10839. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10840. this.stopProgressTask();
  10841. this.startProgressTask();
  10842. this.play(this.videoUrl.toString(),startOffset);
  10843. }
  10844. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  10845. this.mIjkMediaPlayer.start();
  10846. this.setProgress()
  10847. this.CONTROL_PlayStatus = PlayStatus.PLAY
  10848. }
  10849. this.setIsPlaying(true)
  10850. this.updateSessionPlayState(true)
  10851. this.watchStatus();
  10852. this.updateLastPlayTimeStr(this.videoUrl)
  10853. }
  10854. updateLastPlayTimeStr(filePath: string) {
  10855. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  10856. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10857. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  10858. return;
  10859. }
  10860. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  10861. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  10862. if (success) {
  10863. this.getHistoryList(false)
  10864. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  10865. } else {
  10866. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  10867. }
  10868. });
  10869. }
  10870. private completionNum(num: number): string | number {
  10871. if (num < 10) {
  10872. return '0' + num;
  10873. } else {
  10874. return num;
  10875. }
  10876. }
  10877. private stringForTime(timeMs: number): string {
  10878. let totalSeconds: number | string = (timeMs / 1000);
  10879. let newSeconds: number | string = totalSeconds % 60;
  10880. let minutes: number | string = (totalSeconds / 60) % 60;
  10881. let hours: number | string = totalSeconds / 3600;
  10882. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  10883. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  10884. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  10885. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  10886. if (this.isCurrentTime) {
  10887. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  10888. this.oldSeconds = newSeconds
  10889. } else {
  10890. newSeconds = this.oldSeconds
  10891. }
  10892. }
  10893. newSeconds = this.completionNum(newSeconds);
  10894. if (hours > 0) {
  10895. return hours + ":" + minutes + ":" + newSeconds;
  10896. } else {
  10897. return minutes + ":" + newSeconds;
  10898. }
  10899. }
  10900. private setProgress() {
  10901. let position = this.mIjkMediaPlayer.getCurrentPosition();
  10902. let duration = this.mIjkMediaPlayer.getDuration();
  10903. let pos = 0;
  10904. if (duration > 0) {
  10905. this.slideEnable = true;
  10906. let curPercent = position / duration;
  10907. pos = curPercent * 100;
  10908. if (pos > this.PROGRESS_MAX_VALUE) {
  10909. this.progressValue = this.PROGRESS_MAX_VALUE
  10910. } else {
  10911. this.progressValue = pos;
  10912. }
  10913. }
  10914. // LogUtils.getInstance()
  10915. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10916. this.totalTime = this.stringForTime(duration);
  10917. if (position > duration) {
  10918. position = duration;
  10919. }
  10920. this.isCurrentTime = true;
  10921. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  10922. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  10923. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  10924. this.currentTime = this.stringForTime(position);
  10925. this.isCurrentTime = false
  10926. if (this.mIjkMediaPlayer.isPlaying()) {
  10927. this.randomColor =
  10928. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  10929. //如果是开启AB循环
  10930. if(this.isOpenAB){
  10931. if(position >=this.jumpBTime){
  10932. this.seekTo(this.jumpATime+'')
  10933. return
  10934. }
  10935. }
  10936. // 判断是否播放到结束时间
  10937. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  10938. if (position >= duration - this.jumpEndTime * 1000) {
  10939. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  10940. this.CONTROL_PlayStatus = PlayStatus.INIT
  10941. this.startPlayOrResumePlay();
  10942. }else if (this.playType == 2) { //2:正常播放,单曲播完
  10943. this.showRePlay();
  10944. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  10945. this.progressValue = this.PROGRESS_MAX_VALUE;
  10946. this.slideEnable = false;
  10947. this.stop();
  10948. // ToastUtil.showToast('开始重新播放')
  10949. }else{
  10950. this.playNext().catch(() => {
  10951. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  10952. });
  10953. }
  10954. }
  10955. }
  10956. } else {
  10957. this.randomColor = 'rbg(0,0,0)'
  10958. }
  10959. }
  10960. private startProgressTask() {
  10961. let that = this;
  10962. this.updateProgressTimer = setInterval(() => {
  10963. //LogUtils.getInstance().LOGI("startProgressTask");
  10964. if (!that.mDestroyPage) {
  10965. that.setProgress();
  10966. }
  10967. }, 300);
  10968. }
  10969. private stopProgressTask() {
  10970. LogUtils.getInstance().LOGI("stopProgressTask");
  10971. clearInterval(this.updateProgressTimer);
  10972. }
  10973. private showLoadIng() {
  10974. this.loadingVisible = Visibility.Visible;
  10975. this.replayVisible = Visibility.None;
  10976. }
  10977. private hideLoadIng() {
  10978. this.loadingVisible = Visibility.None;
  10979. this.replayVisible = Visibility.None;
  10980. }
  10981. private showRePlay() {
  10982. this.loadingVisible = Visibility.None;
  10983. this.replayVisible = Visibility.Visible;
  10984. }
  10985. private async play(url: string,startOffset?:number) {
  10986. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  10987. console.info('onecold this.url 1= '+url)
  10988. if(!url.toLowerCase().startsWith('http')){
  10989. let hasPermission = await PermissionUtil.activatePermission(url)
  10990. console.info('onecold this.hasPermission 1= '+hasPermission)
  10991. if(!url.includes(this.packName)){
  10992. const file = fs.openSync(url)
  10993. this.videoUrl = file.path
  10994. url= this.videoUrl
  10995. }
  10996. console.info('onecold this.hasPermission 1= '+hasPermission)
  10997. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  10998. }
  10999. let that = this;
  11000. that.showLoadIng();
  11001. this.isOpenAB = false
  11002. //设置XComponent回调的context
  11003. if (!!this.mContext) {
  11004. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  11005. }
  11006. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11007. this.mIjkMediaPlayer.reset();
  11008. }
  11009. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  11010. //设置debug模式
  11011. this.mIjkMediaPlayer.setDebug(false);
  11012. //初始化配置
  11013. this.mIjkMediaPlayer.native_setup();
  11014. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  11015. if(this.volumeSmall){
  11016. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11017. this.mIjkMediaPlayer.setVolume('1', '1');
  11018. }else{
  11019. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11020. }
  11021. }else{
  11022. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11023. }
  11024. //设置视频源
  11025. this.mIjkMediaPlayer.setDataSource(url);
  11026. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  11027. const headers = new Map<string, string>();
  11028. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  11029. headers.set("Accept", "*/*");
  11030. headers.set("Range", "bytes=0-");
  11031. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  11032. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  11033. //如果封面为空,则搜索封面
  11034. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  11035. }
  11036. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  11037. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  11038. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  11039. if (this.currentSong.webdav_account_id) {
  11040. try {
  11041. const webdavManager = WebdavManager.getInstance();
  11042. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  11043. if (webDavHeaders && webDavHeaders.size > 0) {
  11044. webDavHeaders.forEach((value, key) => headers.set(key, value));
  11045. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  11046. } else {
  11047. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  11048. }
  11049. } catch (error) {
  11050. const err = error as Error;
  11051. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  11052. }
  11053. } else {
  11054. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  11055. }
  11056. }
  11057. // 统一设置带认证的请求头
  11058. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  11059. if (this.currentSong&&this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  11060. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  11061. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  11062. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  11063. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  11064. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  11065. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  11066. // 缓冲和播放优化设置
  11067. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  11068. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  11069. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  11070. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  11071. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  11072. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  11073. // 网络相关设置
  11074. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  11075. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  11076. // 重连设置
  11077. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  11078. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  11079. }
  11080. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  11081. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  11082. // }
  11083. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  11084. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  11085. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  11086. const fileSize = await this.getFileSize(this.videoUrl);
  11087. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  11088. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  11089. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  11090. }
  11091. // 使用软件解码(通常比硬件解码更节省内存)
  11092. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  11093. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  11094. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  11095. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  11096. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  11097. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  11098. //停止预读的最小帧数
  11099. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  11100. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  11101. // 设置其他缓冲相关选项
  11102. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  11103. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  11104. //启动预加载
  11105. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  11106. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  11107. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  11108. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  11109. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  11110. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  11111. // 因此需要播放器丢包,才不会累积延时
  11112. // 这个和第三个参数packet-buffering无关。
  11113. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  11114. // 无限制收流
  11115. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  11116. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  11117. // 屏幕常亮
  11118. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  11119. // 设置超时
  11120. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  11121. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  11122. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  11123. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  11124. // 变速播放
  11125. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  11126. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11127. let Speed = this.mIjkMediaPlayer.getSpeed()
  11128. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  11129. //是否开启循环播放
  11130. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  11131. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  11132. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  11133. if (height === 0) {
  11134. return;
  11135. }
  11136. const va = width / height;
  11137. const vpa = that.videoParentAspectRatio;
  11138. if (vpa > va) {
  11139. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  11140. } else {
  11141. that.videoWidth = '100%';
  11142. }
  11143. if (width && height) {
  11144. that.videoAspectRatio = width / height;
  11145. }
  11146. LogUtils.getInstance()
  11147. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  11148. that.hideLoadIng();
  11149. }
  11150. }
  11151. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  11152. let mOnPreparedListener: OnPreparedListener = {
  11153. onPrepared: async () => {
  11154. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  11155. try {
  11156. //保存碰一碰分享的当前的歌曲
  11157. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  11158. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11159. await this.initLyric(lyricPath);
  11160. setTimeout(() => {
  11161. this.avSessionController.initAvSession(false);
  11162. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  11163. this.setAvSessionListener();
  11164. this.updateSessionPlayState(true)
  11165. this.setCurrentPlayMode()
  11166. }, 500)
  11167. if(startOffset&&startOffset>0){//cue分轨播放
  11168. this.seekTo(startOffset + "");
  11169. this.saveLastPlayList()
  11170. return
  11171. }
  11172. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11173. let timeoutPlay = 0
  11174. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11175. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  11176. timeoutPlay = 1000
  11177. }
  11178. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  11179. if (this.modeType === 0) { //文件夹
  11180. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11181. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  11182. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  11183. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  11184. } else if (this.modeType === 1) { //媒体库
  11185. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  11186. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  11187. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  11188. } else if (this.modeType === 2) { //艺术家
  11189. if (this.currentSong?.artist) {
  11190. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  11191. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  11192. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  11193. }
  11194. } else if (this.modeType === 3) { //专辑
  11195. if (this.currentSong?.album) {
  11196. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  11197. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  11198. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  11199. }
  11200. }
  11201. this.duration = this.mIjkMediaPlayer.getDuration()
  11202. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  11203. if (this.mIjkMediaPlayer != null) {
  11204. let jumpTopTimeMs = this.jumpTopTime*1000;
  11205. if (jumpTopTimeMs <= this.duration) {
  11206. // 调用 seekTo 方法,跳到指定时间
  11207. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  11208. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  11209. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11210. console.log('onecold position = '+position);
  11211. if (position > jumpTopTimeMs) {
  11212. jumpTopTimeMs = position
  11213. }
  11214. }
  11215. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11216. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11217. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  11218. }
  11219. }, timeoutPlay)
  11220. } else {
  11221. // 提示用户无法跳过
  11222. ToastUtil.showToast('跳过时间超过视频时长');
  11223. }
  11224. }
  11225. } else {
  11226. this.jumpTopTime = 0
  11227. this.jumpEndTime = 0
  11228. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  11229. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  11230. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  11231. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  11232. //记忆播放(每一首都会记忆播放)
  11233. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11234. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11235. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  11236. this.restorePlaybackPosition() //读取播放记忆功能
  11237. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  11238. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  11239. this.restorePlaybackPosition() //读取播放记忆功能
  11240. }
  11241. this.isFirstStartPlay = false
  11242. }, timeoutPlay)
  11243. } else {
  11244. this.isFirstStartPlay = false
  11245. }
  11246. }
  11247. this.saveLastPlayList()
  11248. } catch (error) {
  11249. let err: BusinessError = error as BusinessError;
  11250. console.error('onecold failed with err: ' + JSON.stringify(err));
  11251. }
  11252. }
  11253. }
  11254. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  11255. let mOnTimedTextListener: OnTimedTextListener = {
  11256. onTimedText: () => {
  11257. }
  11258. }
  11259. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  11260. let mOnCompletionListener: OnCompletionListener = {
  11261. onCompletion: () => {
  11262. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  11263. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  11264. // 异步调用playNext
  11265. this.playNext().catch(() => {
  11266. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  11267. });
  11268. } else if (this.playType == 1) { //1:单片重复播放
  11269. this.CONTROL_PlayStatus = PlayStatus.INIT
  11270. console.info('onecold startPlayOrResumePlay 10592')
  11271. that.startPlayOrResumePlay();
  11272. } else if (this.playType == 2) { //2:正常播放,单曲播完
  11273. that.showRePlay();
  11274. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  11275. that.progressValue = this.PROGRESS_MAX_VALUE;
  11276. that.slideEnable = false;
  11277. that.stop();
  11278. // ToastUtil.showToast('开始重新播放')
  11279. } else if (this.playType == 3) { //3:随机播放
  11280. // 异步调用randomPlay
  11281. this.randomPlay().catch(() => {
  11282. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  11283. });
  11284. }
  11285. }
  11286. }
  11287. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  11288. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  11289. onBufferingUpdate: (percent: number) => {
  11290. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  11291. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  11292. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  11293. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  11294. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  11295. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  11296. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  11297. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  11298. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  11299. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  11300. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  11301. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  11302. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  11303. let Looping = this.mIjkMediaPlayer.isLooping()
  11304. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  11305. }
  11306. }
  11307. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  11308. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  11309. onSeekComplete: () => {
  11310. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  11311. console.info('onecold startPlayOrResumePlay 10643')
  11312. that.startPlayOrResumePlay();
  11313. }
  11314. }
  11315. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  11316. let mOnInfoListener: OnInfoListener = {
  11317. onInfo: (what: number, extra: number) => {
  11318. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  11319. that.hideLoadIng();
  11320. }
  11321. }
  11322. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  11323. let mOnErrorListener: OnErrorListener = {
  11324. onError: (what: number, extra: number) => {
  11325. this.stopProgressTask();
  11326. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  11327. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  11328. // 检查是否为WebDAV播放错误
  11329. let isWebDavError = false;
  11330. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV && this.currentSong.filePath) {
  11331. try {
  11332. const globalContext = GlobalContext.getContext();
  11333. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  11334. if (webDavAuthInfo) {
  11335. isWebDavError = true;
  11336. }
  11337. } catch (error) {
  11338. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  11339. }
  11340. }
  11341. if (isWebDavError) {
  11342. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  11343. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  11344. // this.currentWebDavAuthInfo = null;
  11345. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  11346. // 根据错误代码提供更具体的错误信息
  11347. let errorMessage = "WebDAV播放失败";
  11348. if (what === -1) { // 网络错误
  11349. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  11350. } else if (what === -1004) { // HTTP 404
  11351. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  11352. } else if (what === -1001) { // 超时
  11353. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  11354. } else if (what === -1003) { // 无法解析主机
  11355. errorMessage = "无法连接到WebDAV服务器";
  11356. }
  11357. ToastUtil.showToast(errorMessage);
  11358. } else {
  11359. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11360. !this.videoUrl.startsWith('http://') &&
  11361. !this.videoUrl.startsWith('https://') &&
  11362. !FileUtil.accessSync(this.videoUrl)) {
  11363. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  11364. } else {
  11365. ToastUtil.showToast(getContext()
  11366. .resourceManager
  11367. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  11368. }
  11369. }
  11370. that.hideLoadIng();
  11371. }
  11372. }
  11373. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  11374. this.mIjkMediaPlayer.setMessageListener();
  11375. this.mIjkMediaPlayer.prepareAsync();
  11376. this.mIjkMediaPlayer.start();
  11377. }
  11378. //保存最后播放的那首歌和已经对应的播放列表
  11379. saveLastPlayList() {
  11380. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  11381. PreferencesUtil.putSync('LastMusicList', this.songList)
  11382. }
  11383. // 清空播放记录
  11384. clearVideoHistory() {
  11385. this.table.clearPlayHistory((success: boolean, error?: string) => {
  11386. if (success) {
  11387. this.historyList = [];
  11388. this.updateListData(this.historyList)
  11389. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  11390. ToastUtil.showToast('清空播放记录成功')
  11391. } else {
  11392. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  11393. }
  11394. });
  11395. }
  11396. public async setAvSessionListener() {
  11397. if (!this.avSessionController) {
  11398. return;
  11399. }
  11400. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  11401. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  11402. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  11403. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  11404. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  11405. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  11406. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  11407. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  11408. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  11409. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  11410. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  11411. }
  11412. setLoopMode() {
  11413. let itype = this.playType + 1
  11414. if (itype >= 4) {
  11415. this.playType = 0
  11416. ToastUtil.showToast('连续播放')
  11417. } else if (itype === 1) {
  11418. this.playType = 1
  11419. ToastUtil.showToast('单曲循环')
  11420. } else if (itype === 2) {
  11421. this.playType = 2
  11422. ToastUtil.showToast('单曲播完')
  11423. } else if (itype === 3) {
  11424. this.playType = 3
  11425. ToastUtil.showToast('随机播放')
  11426. } else if (itype === 0) {
  11427. this.playType = 0
  11428. ToastUtil.showToast('连续播放')
  11429. }
  11430. PreferencesUtil.putSync('musicPlayType', this.playType)
  11431. this.setCurrentPlayMode()
  11432. }
  11433. private sessionSetLoopModeCallback = (mode: number) => {
  11434. if (this.mIjkMediaPlayer != null) {
  11435. ToastUtil.showToast('当前播放模式:' + mode)
  11436. Logger.info('onecold 当前播放模式= ' + mode)
  11437. let hmPlayMode = mode + 1
  11438. if (hmPlayMode >= 4) {
  11439. hmPlayMode = 0
  11440. }
  11441. if (hmPlayMode === 1) {
  11442. this.playType = 1
  11443. ToastUtil.showToast('单曲循环')
  11444. } else if (hmPlayMode === 0) {
  11445. this.playType = 2
  11446. ToastUtil.showToast('单曲播完')
  11447. } else if (hmPlayMode === 3) {
  11448. this.playType = 3
  11449. ToastUtil.showToast('随机播放')
  11450. } else if (hmPlayMode === 2) {
  11451. this.playType = 0
  11452. ToastUtil.showToast('连续播放')
  11453. }
  11454. PreferencesUtil.putSync('musicPlayType', this.playType)
  11455. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  11456. let playBackState: avSession.AVPlaybackState = {
  11457. loopMode: hmPlayMode,
  11458. };
  11459. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  11460. console.info(`set setLoopMode AVPlaybackState successfully`);
  11461. }).catch((err: BusinessError) => {
  11462. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11463. });
  11464. }
  11465. }
  11466. setCurrentPlayMode() {
  11467. if (!this.avSessionController) {
  11468. return;
  11469. }
  11470. let mLoopMode = 0
  11471. switch (this.playType) {
  11472. case 0:
  11473. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  11474. break;
  11475. case 1:
  11476. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  11477. break;
  11478. case 2:
  11479. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  11480. break;
  11481. case 3:
  11482. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  11483. break;
  11484. }
  11485. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  11486. let playBState: avSession.AVPlaybackState = {
  11487. loopMode: mLoopMode,
  11488. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  11489. };
  11490. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  11491. console.info(`set setLoopMode AVPlaybackState successfully`);
  11492. }).catch((err: BusinessError) => {
  11493. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11494. });
  11495. }
  11496. private sessionToggleFavoriteCallback = (assetId: string) => {
  11497. if (this.mIjkMediaPlayer != null && this.currentSong) {
  11498. console.info(`on toggleFavorite `);
  11499. // 应用收到收藏命令,进行收藏处理。
  11500. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  11501. this.doFav(this.currentSong)
  11502. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  11503. let playbackState: avSession.AVPlaybackState = {
  11504. isFavorite: !this.isFac,
  11505. };
  11506. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  11507. console.info(`SetAVPlaybackState successfully`);
  11508. }).catch((err: BusinessError) => {
  11509. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  11510. });
  11511. }
  11512. }
  11513. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  11514. device: avSession.OutputDeviceInfo) => {
  11515. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  11516. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11517. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  11518. await this.startCasting();
  11519. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11520. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  11521. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  11522. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  11523. if (device) {
  11524. this.endCasting();
  11525. }
  11526. }
  11527. };
  11528. private async startCasting() {
  11529. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11530. this.setPlaybackStateChangeListener();
  11531. this.pause();
  11532. this.initQueueItem();
  11533. this.prepare();
  11534. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11535. refToIsCasting?.set(true);
  11536. this.castSeek = true;
  11537. this.isCastPlaying = true;
  11538. }
  11539. async changeCasting() {
  11540. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11541. this.initQueueItem();
  11542. this.prepare();
  11543. this.setPlaybackStateChangeListener();
  11544. this.isCastPlaying = true;
  11545. this.castSeek = true;
  11546. }
  11547. public endCasting() {
  11548. this.avSessionController.getAvSession()?.stopCasting();
  11549. this.stopCast();
  11550. this.isCastPlaying = false;
  11551. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11552. refToIsCasting?.set(false);
  11553. this.pause();
  11554. this.setIsPlaying(false);
  11555. // if (this.curIndex === this.curSource.index) {
  11556. // this.play
  11557. // this.seek(this.currentTime * 1000);
  11558. // this.setIsPlaying(true);
  11559. // } else {
  11560. // this.pauseVideo();
  11561. // this.setIsPlaying(false);
  11562. // }
  11563. }
  11564. public setIsPlaying(isPlayer: boolean) {
  11565. this.isPlaying = isPlayer;
  11566. // 发送播放状态变化事件给歌单详情页面
  11567. try {
  11568. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  11569. const currentFilePath = this.currentSong?.filePath || ''
  11570. const eventData: emitter.EventData = {
  11571. data: {
  11572. isPlaying: this.isPlaying,
  11573. curIndex: this.curIndex,
  11574. currentFilePath: currentFilePath
  11575. }
  11576. };
  11577. emitter.emit(eventPlaybackStatus, eventData)
  11578. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  11579. } catch (error) {
  11580. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  11581. }
  11582. }
  11583. private setPlaybackStateChangeListener(): void {
  11584. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  11585. this.castController?.on('endOfStream', this.reloadCasting);
  11586. this.castController?.on('playNext', this.playNextCallback);
  11587. this.castController?.on('playPrevious', this.playPreviousCallback);
  11588. }
  11589. private updateSessionPlayState(isPlay: boolean): void {
  11590. // if(!this.isBgPlayOpen)
  11591. // return
  11592. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  11593. this.setAVSessionPlayState({
  11594. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  11595. position: {
  11596. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  11597. updateTime: new Date().getTime()
  11598. }
  11599. });
  11600. }
  11601. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  11602. this.avSessionController.setAvSessionPlayState(playbackState)
  11603. }
  11604. private positionChange(position: number) {
  11605. this.currentTime2 = position / 1000;
  11606. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  11607. }
  11608. private playDurationChange(duration: number) {
  11609. this.duration = duration;
  11610. this.durationTime = Math.floor(this.duration / 1000);
  11611. this.durationStringTime = secondToTime((this.durationTime));
  11612. }
  11613. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  11614. const duration = playbackState?.extras?.duration;
  11615. if (typeof duration === 'number') {
  11616. this.playDurationChange(duration as number);
  11617. }
  11618. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  11619. this.positionChange(playbackState?.position?.elapsedTime);
  11620. }
  11621. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  11622. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  11623. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  11624. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  11625. this.isCastPlaying = false;
  11626. }
  11627. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  11628. this.isCastPlaying = true;
  11629. }
  11630. };
  11631. private reloadCasting = async () => {
  11632. let item = this.songList[this.curIndex];
  11633. let uri = fileUri.getUriFromPath(item.filePath);
  11634. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11635. // description.startPosition = 0;
  11636. this.castItem = {
  11637. itemId: this.curIndex,
  11638. description: {
  11639. assetId: item.filePath,
  11640. title: item.name,
  11641. artist: '',
  11642. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11643. // mediaUri: item.filePath,
  11644. fdSrc: {
  11645. fd: file.fd
  11646. },
  11647. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11648. mediaType: 'VIDEO',
  11649. mediaSize: item.videoSize,
  11650. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11651. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11652. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11653. duration: this.duration,
  11654. // albumCoverUri: 'https://www.example.jpeg',
  11655. // albumTitle: '《ExampleAlbum》',
  11656. appName: this.appName,
  11657. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11658. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11659. }
  11660. };
  11661. this.prepare();
  11662. this.isCastPlaying = true;
  11663. };
  11664. public playNextCallback = (): void => {
  11665. this.playNext().catch(() => {
  11666. Logger.error('heanup playNextCallback', `播放下一首失败`);
  11667. });
  11668. };
  11669. public playPreviousCallback = (): void => {
  11670. this.playPrevious().catch(() => {
  11671. Logger.error('heanup playNextCallback', `播放上一首失败`);
  11672. });
  11673. };
  11674. async prepare() {
  11675. await this.castController?.prepare(this.castItem);
  11676. await this.castController?.start(this.castItem);
  11677. }
  11678. public initQueueItem() {
  11679. let item = this.songList[this.curIndex];
  11680. let time = this.currentTime;
  11681. let uri = fileUri.getUriFromPath(item.filePath);
  11682. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11683. this.castItem = {
  11684. itemId: this.curIndex,
  11685. description: {
  11686. assetId: item.filePath,
  11687. title: item.name,
  11688. artist: '',
  11689. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11690. fdSrc: {
  11691. fd: file.fd
  11692. },
  11693. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11694. mediaType: 'AUDIO',
  11695. mediaSize: item.videoSize,
  11696. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11697. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11698. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11699. duration: this.duration,
  11700. // albumCoverUri: 'https://www.example.jpeg',
  11701. // albumTitle: '《ExampleAlbum》',
  11702. appName: this.appName,
  11703. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11704. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11705. }
  11706. };
  11707. }
  11708. async stopCast() {
  11709. try {
  11710. this.castController?.off('playbackStateChange');
  11711. this.castController?.off('endOfStream');
  11712. this.castController?.off('playNext');
  11713. this.castController?.off('playPrevious');
  11714. this.castController?.off('error');
  11715. } catch (error) {
  11716. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  11717. }
  11718. }
  11719. private sessionPlayCallback = (): void => {
  11720. console.info('onecold playOrPause 11050')
  11721. this.playOrPause()
  11722. };
  11723. private sessionPauseCallback = (): void => {
  11724. console.info('onecold playOrPause 11054')
  11725. this.pause()
  11726. };
  11727. private playOrPause() {
  11728. if (!this.debounce()) {
  11729. return;
  11730. }
  11731. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11732. this.pause();
  11733. } else {
  11734. console.info('onecold startPlayOrResumePlay 11064')
  11735. this.startPlayOrResumePlay();
  11736. this.playChange()
  11737. }
  11738. }
  11739. private sessionPlayNextCallback = (): void => {
  11740. this.playNext().catch(() => {
  11741. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  11742. });
  11743. };
  11744. private sessionPlayPreviousCallback = (): void => {
  11745. this.playPrevious().catch(() => {
  11746. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  11747. });
  11748. };
  11749. private sessionStopCallback = (): void => {
  11750. this.stop()
  11751. };
  11752. private sessionFastForwardCallback = (time?: number) => {
  11753. if (!time) {
  11754. return;
  11755. }
  11756. if (this.mIjkMediaPlayer != null) {
  11757. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11758. let seeTime = curPosition + time * 1000;
  11759. // 限制 seekValue 在合法范围内
  11760. if (seeTime < 0) {
  11761. seeTime = 0;
  11762. } else if (seeTime > this.duration) {
  11763. seeTime = this.duration;
  11764. }
  11765. Logger.info('onecold seeTime= ' + seeTime)
  11766. this.setSeekToActionProgress(seeTime)
  11767. this.seekTo(seeTime + "")
  11768. }
  11769. };
  11770. /**
  11771. * Gesture method onActionUpdate.
  11772. *
  11773. * @param event Gesture event.手势拖动设置快进和后退
  11774. */
  11775. private setSeekToActionProgress(position: number) {
  11776. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  11777. let duration = this.mIjkMediaPlayer.getDuration();
  11778. let pos = 0;
  11779. if (duration > 0) {
  11780. this.slideEnable = true;
  11781. let curPercent = position / duration;
  11782. pos = curPercent * 100;
  11783. if (pos > this.PROGRESS_MAX_VALUE) {
  11784. this.progressValue = this.PROGRESS_MAX_VALUE
  11785. } else {
  11786. this.progressValue = pos;
  11787. }
  11788. }
  11789. // LogUtils.getInstance()
  11790. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11791. this.totalTime = this.stringForTime(duration);
  11792. if (position > duration) {
  11793. position = duration;
  11794. }
  11795. this.isCurrentTime = true;
  11796. this.currentTime = this.stringForTime(position);
  11797. this.isCurrentTime = false
  11798. }
  11799. private sessionRewindCallback = (time?: number) => {
  11800. if (!time) {
  11801. return;
  11802. }
  11803. if (this.mIjkMediaPlayer != null) {
  11804. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11805. let seeTime = curPosition - time * 1000;
  11806. // 限制 seekValue 在合法范围内
  11807. if (seeTime < 0) {
  11808. seeTime = 0;
  11809. } else if (seeTime > this.duration) {
  11810. seeTime = this.duration;
  11811. }
  11812. Logger.info('onecold seeTime= ' + seeTime)
  11813. this.setSeekToActionProgress(seeTime)
  11814. this.seekTo(seeTime + "")
  11815. }
  11816. };
  11817. private sessionSeekCallback = (seekTime: number) => {
  11818. if (this.mIjkMediaPlayer != null) {
  11819. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11820. this.seekTo(seekTime + "")
  11821. }
  11822. };
  11823. private async getFileSize(filePath: string): Promise<number> {
  11824. try {
  11825. const stat = await fs.stat(filePath);
  11826. return stat.size;
  11827. } catch (err) {
  11828. console.error('Failed to get file size: ' + err.message);
  11829. return 0;
  11830. }
  11831. }
  11832. private pause() {
  11833. if (this.mIjkMediaPlayer.isPlaying()) {
  11834. this.savePlaybackPosition();
  11835. this.mIjkMediaPlayer.pause();
  11836. this.setProgress();
  11837. this.mDestroyPage = true;
  11838. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  11839. this.updateSessionPlayState(false)
  11840. this.playChange()
  11841. if (this.pipController) {
  11842. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11843. PiPWindow.PiPControlStatus.PAUSE);
  11844. }
  11845. }
  11846. }
  11847. private stop() {
  11848. this.savePlaybackPosition();
  11849. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11850. this.mIjkMediaPlayer.stop();
  11851. this.mIjkMediaPlayer.release();
  11852. this.stopProgressTask();
  11853. this.updateSessionPlayState(false)
  11854. this.playChange()
  11855. this.watchStatus();
  11856. }
  11857. //保持记忆播放功能
  11858. private savePlaybackPosition() {
  11859. if (this.mIjkMediaPlayer != null) {
  11860. const position = this.mIjkMediaPlayer.getCurrentPosition();
  11861. // ToastUtil.showToast('保存记忆播放 = ' + position)
  11862. const duration = this.mIjkMediaPlayer.getDuration();
  11863. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  11864. // 如果播放位置接近视频末尾,则保存 position 为 0
  11865. const playbackPosition = (duration - position < threshold) ? 0 : position;
  11866. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  11867. }
  11868. }
  11869. //获取记忆播放功能
  11870. private restorePlaybackPosition() {
  11871. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11872. // ToastUtil.showToast('position = ' + position)
  11873. if (this.mIjkMediaPlayer != null && position > 0) {
  11874. // ToastUtil.showToast('seekTo = ' + position)
  11875. this.seekTo(position + "");
  11876. }
  11877. }
  11878. private seekTo(value: string) {
  11879. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  11880. ToastUtil.showToast('wma格式不支持拖动快进。')
  11881. return
  11882. }
  11883. this.isSeekTo = true
  11884. this.mIjkMediaPlayer.seekTo(value);
  11885. console.info('onecold startPlayOrResumePlay 11227')
  11886. // this.startPlayOrResumePlay()
  11887. // 在这里恢复计时器状态
  11888. this.setProgress()
  11889. this.isSeekTo = false
  11890. }
  11891. // 添加到下一首播放
  11892. private addToNextPlay(song: VideoItem) {
  11893. if (!this.debounce()) {
  11894. return;
  11895. }
  11896. if (this.currentSong) {
  11897. if (this.currentSong === song) {
  11898. ToastUtil.showToast('当前已经在播放这首歌了!')
  11899. return
  11900. }
  11901. }
  11902. // 如果未开始播放或队列为空
  11903. if (this.curIndex === -1 || this.songList.length === 0) {
  11904. this.songList = [song];
  11905. this.curIndex = 0;
  11906. this.doPlay(song)
  11907. return;
  11908. }
  11909. // 插入到当前索引+1的位置
  11910. const insertPos = this.curIndex + 1;
  11911. this.songList.splice(insertPos, 0, song);
  11912. this.songList = [...this.songList]; // 触发状态更新
  11913. this.sonDataSource.pushArrayData(this.songList)
  11914. ToastUtil.showToast('已添加至下一首播放')
  11915. }
  11916. //后退10s,可再设置设置默认几秒
  11917. backForward() {
  11918. if(this.mIjkMediaPlayer){
  11919. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11920. let value = pos - Number(this.fastForwardSeconds) * 1000;
  11921. this.seekTo(value+"");
  11922. }
  11923. }
  11924. //快进10s,可再设置设置默认几秒
  11925. fastForward() {
  11926. if(this.mIjkMediaPlayer){
  11927. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11928. let value = pos + Number(this.fastForwardSeconds) * 1000;
  11929. this.seekTo(value+"");
  11930. }
  11931. }
  11932. //下一个
  11933. private async playNext() {
  11934. if (!this.debounce()) {
  11935. return;
  11936. }
  11937. if (this.playType == 3) { //3:随机播放
  11938. await this.randomPlay()
  11939. return;
  11940. }
  11941. if (ArrayUtil.isNotEmpty(this.songList)) {
  11942. if (this.curIndex == this.songList.length - 1) {
  11943. this.curIndex = 0;
  11944. } else {
  11945. this.curIndex++;
  11946. }
  11947. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11948. this.stop();
  11949. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  11950. this.currentSong = this.songList[this.curIndex];
  11951. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  11952. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  11953. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  11954. this.artist = this.songList[this.curIndex].artist
  11955. this.name = this.songList[this.curIndex].name
  11956. //this.cover = this.songList[this.curIndex].pixelMapPath
  11957. this.changeImageAnimation()
  11958. }
  11959. }
  11960. changeImageAnimation() {
  11961. if(this.openSkipSongAnimate){
  11962. // 第一步:淡出动画
  11963. this.getUIContext()?.animateTo({
  11964. duration: 500,
  11965. curve: Curve.EaseOut,
  11966. }, () => {
  11967. this.opacityValueImage = 0.1;
  11968. if(this.isCoverRectangle){
  11969. this.scaleValueImage = 0.88
  11970. }
  11971. });
  11972. // 第二步:切换图片后淡入
  11973. setTimeout(() => {
  11974. this.cover = this.songList[this.curIndex].pixelMapPath
  11975. this.getUIContext()?.animateTo({
  11976. duration: 500,
  11977. curve: Curve.EaseIn,
  11978. }, () => {
  11979. this.opacityValueImage = 1;
  11980. this.scaleValueImage = 1 // 图标恢复到原始大小
  11981. this.startPlayOrResumePlay()
  11982. });
  11983. }, 500);
  11984. }else{
  11985. this.cover = this.songList[this.curIndex].pixelMapPath
  11986. this.startPlayOrResumePlay()
  11987. }
  11988. }
  11989. // 存储已播放的歌曲索引
  11990. private playedIndices: Set<number> = new Set();
  11991. //随机播放
  11992. private async randomPlay() {
  11993. // if (!this.debounce()) {
  11994. // return;
  11995. // }
  11996. if (ArrayUtil.isNotEmpty(this.songList)) {
  11997. if (this.songList.length > 3) {
  11998. // 如果所有歌曲都播放过一次,清空已播放索引集合
  11999. if (this.playedIndices.size === this.songList.length) {
  12000. this.playedIndices.clear();
  12001. }
  12002. // 随机选择一个未播放的歌曲索引
  12003. let newIndex: number;
  12004. // 添加超时机制防止无限循环
  12005. let attempt = 0;
  12006. const maxAttempts = 100; // 根据需求调整
  12007. do {
  12008. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  12009. attempt++;
  12010. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  12011. if (attempt >= maxAttempts) {
  12012. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  12013. newIndex = Math.floor(Math.random() * this.songList.length);
  12014. }
  12015. this.curIndex = newIndex;
  12016. this.playedIndices.add(newIndex);
  12017. } else {
  12018. // 当歌曲数量小于或等于3时,直接播放下一首
  12019. if (this.curIndex == this.songList.length - 1) {
  12020. this.curIndex = 0;
  12021. } else {
  12022. this.curIndex++;
  12023. }
  12024. }
  12025. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12026. this.stop();
  12027. this.currentSong = this.songList[this.curIndex];
  12028. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12029. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12030. this.name = this.songList[this.curIndex].name;
  12031. this.artist = this.songList[this.curIndex].artist
  12032. // this.cover = this.songList[this.curIndex].pixelMapPath
  12033. this.changeImageAnimation()
  12034. }
  12035. }
  12036. private async playIndex(index: number) {
  12037. if (!this.debounce()) {
  12038. return;
  12039. }
  12040. if (ArrayUtil.isNotEmpty(this.songList)) {
  12041. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12042. this.stop();
  12043. this.curIndex = index;
  12044. this.currentSong = this.songList[index];
  12045. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12046. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12047. this.name = this.currentSong.name
  12048. this.artist = this.currentSong.artist
  12049. this.changeImageAnimation()
  12050. }
  12051. }
  12052. //上一个
  12053. private async playPrevious() {
  12054. if (!this.debounce()) {
  12055. return;
  12056. }
  12057. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  12058. this.randomModePlayFromHistory()
  12059. return;
  12060. }
  12061. if (this.curIndex == 0) {
  12062. this.curIndex = this.songList.length - 1;
  12063. } else {
  12064. this.curIndex--;
  12065. }
  12066. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12067. this.stop();
  12068. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12069. this.currentSong = this.songList[this.curIndex];
  12070. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12071. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12072. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12073. this.name = this.songList[this.curIndex].name
  12074. this.artist = this.songList[this.curIndex].artist
  12075. this.changeImageAnimation()
  12076. }
  12077. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  12078. private async randomModePlayFromHistory() {
  12079. if (this.historyList.length >= 2) {
  12080. // 播放历史记录的第二首
  12081. const prevSong = this.historyList[1];
  12082. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  12083. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12084. this.stop();
  12085. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  12086. this.currentSong = prevSong;
  12087. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  12088. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12089. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12090. this.cover = prevSong.pixelMapPath
  12091. this.artist = prevSong.artist
  12092. this.name = prevSong.name;
  12093. console.info('onecold startPlayOrResumePlay 11434')
  12094. this.startPlayOrResumePlay();
  12095. } else {
  12096. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  12097. if (this.curIndex === 0) {
  12098. this.curIndex = this.songList.length - 1;
  12099. } else {
  12100. this.curIndex--;
  12101. }
  12102. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12103. this.stop();
  12104. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12105. this.currentSong = this.songList[this.curIndex];
  12106. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12107. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12108. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12109. this.artist = this.songList[this.curIndex].artist
  12110. this.name = this.songList[this.curIndex].name;
  12111. this.changeImageAnimation()
  12112. }
  12113. }
  12114. debounce() {
  12115. const delay = 600;
  12116. let cur = new Date().getTime();
  12117. if (cur - this.last > delay) {
  12118. this.last = cur;
  12119. return true;
  12120. }
  12121. return false;
  12122. }
  12123. /**
  12124. * Sets whether the screen is a constant based on the playback status.
  12125. */
  12126. watchStatus() {
  12127. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  12128. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12129. this.windowClass.setWindowKeepScreenOn(true);
  12130. } else {
  12131. this.windowClass.setWindowKeepScreenOn(false);
  12132. }
  12133. }
  12134. /**
  12135. * Volume gesture method onActionStart.
  12136. *
  12137. * @param event Gesture event.
  12138. */
  12139. private customDialogComponentIdMM: number = 0
  12140. @Builder
  12141. customDialogComponentMM() {
  12142. Column() {
  12143. Row() {
  12144. Blank()
  12145. Text('验证密码')
  12146. .fontSize(22)
  12147. .fontColor($r('app.color.pri_bg'))
  12148. .margin({ top: 18 })
  12149. Blank()
  12150. Image($r('app.media.close'))
  12151. .fillColor(Color.White)
  12152. .margin({ top: 18, right: 18 })
  12153. .width(20)
  12154. .onClick(() => {
  12155. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12156. })
  12157. }
  12158. .width('100%') // 使Row占据整个宽度
  12159. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  12160. Verify({
  12161. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  12162. });
  12163. }.height('60%')
  12164. .backgroundColor($r('app.color.index_background'))
  12165. .justifyContent(FlexAlign.SpaceBetween)
  12166. }
  12167. private handleVerifyCompleted(isSuccess: boolean) {
  12168. if (isSuccess) {
  12169. console.log('验证成功');
  12170. // 在这里处理验证成功后的逻辑
  12171. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12172. this.currentPath = this.lockPath
  12173. this.getSortedFiles(this.currentPath)
  12174. } else {
  12175. // console.log('验证失败');
  12176. ToastUtil.showToast('验证失败')
  12177. }
  12178. }
  12179. private showVerifyDialog() {
  12180. promptAction.openCustomDialog({
  12181. transition: TransitionEffect.asymmetric(
  12182. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  12183. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12184. ,
  12185. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  12186. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12187. ),
  12188. builder: () => {
  12189. this.customDialogComponentMM()
  12190. },
  12191. isModal: true,
  12192. autoCancel: true,
  12193. maskColor: Color.Transparent,
  12194. alignment: DialogAlignment.Bottom,
  12195. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  12196. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  12197. console.log("dialog onWillDismiss")
  12198. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  12199. dismissDialogAction.dismiss()
  12200. }
  12201. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  12202. dismissDialogAction.dismiss()
  12203. }
  12204. }
  12205. }).then((dialogId: number) => {
  12206. this.customDialogComponentIdMM = dialogId
  12207. })
  12208. }
  12209. //左滑操作 移动文件 重命名 删除等操作
  12210. @Builder
  12211. DeleteButton(item: VideoItem, index: number, filePath: string) {
  12212. Row() {
  12213. //加入收藏
  12214. Button() {
  12215. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  12216. .fillColor(Color.White)
  12217. .width(20)
  12218. }
  12219. .width(40)
  12220. .height(40)
  12221. .type(ButtonType.Circle)
  12222. .backgroundColor(this.themeColor)
  12223. .margin(5)
  12224. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12225. .onClick(() => {
  12226. if (item) {
  12227. this.doFav(item)
  12228. }
  12229. })
  12230. //加入下一首播放
  12231. Button() {
  12232. Image($r('app.media.next_to_play'))
  12233. .fillColor(Color.White)
  12234. .width(20)
  12235. }
  12236. .width(40)
  12237. .height(40)
  12238. .type(ButtonType.Circle)
  12239. .backgroundColor(this.themeColor)
  12240. .margin(5)
  12241. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12242. .onClick(() => {
  12243. this.addToNextPlay(item);
  12244. })
  12245. //复制文件
  12246. Button() {
  12247. Image($r('app.media.copy'))
  12248. .fillColor(Color.White)
  12249. .width(20)
  12250. }
  12251. .width(40)
  12252. .height(40)
  12253. .type(ButtonType.Circle)
  12254. .backgroundColor(this.themeColor)
  12255. .margin(5)
  12256. .id(filePath + 'copy')
  12257. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12258. .onClick(() => {
  12259. this.showCopyDialog(false, item, index, filePath + 'copy');
  12260. })
  12261. //移动文件
  12262. Button() {
  12263. Image($r('app.media.cut'))
  12264. .fillColor(Color.White)
  12265. .width(20)
  12266. }
  12267. .width(40)
  12268. .height(40)
  12269. .type(ButtonType.Circle)
  12270. .backgroundColor(this.themeColor)
  12271. .margin(5)
  12272. .id(filePath)
  12273. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12274. .onClick(() => {
  12275. this.showCutDialog(false, item, index, filePath);
  12276. })
  12277. Button() {
  12278. Image($r('app.media.cut_current'))
  12279. .fillColor(Color.White)
  12280. .width(20)
  12281. }
  12282. .width(40)
  12283. .height(40)
  12284. .type(ButtonType.Circle)
  12285. .backgroundColor(this.themeColor)
  12286. .margin(5)
  12287. .id(filePath + 'current')
  12288. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  12289. (this.isHasDir ? Visibility.Visible : Visibility.None))
  12290. .onClick(() => {
  12291. this.showCutDialog(true, item, index, filePath + 'current');
  12292. })
  12293. //重命名
  12294. Button() {
  12295. Image($r('app.media.rename2'))
  12296. .fillColor(Color.White)
  12297. .width(20)
  12298. }
  12299. .width(40)
  12300. .height(40)
  12301. .type(ButtonType.Circle)
  12302. .backgroundColor(this.themeColor)
  12303. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12304. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  12305. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  12306. .margin(5)
  12307. .onClick(() => {
  12308. this.showReNameDialog(item, index + '', filePath)
  12309. })
  12310. Button() {
  12311. Image($r('app.media.delete2'))
  12312. .fillColor(Color.White)
  12313. .width(20)
  12314. }
  12315. .width(40)
  12316. .height(40)
  12317. .type(ButtonType.Circle)
  12318. .backgroundColor(this.themeColor)
  12319. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12320. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  12321. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  12322. .margin(5)
  12323. .onClick(() => {
  12324. this.selectedFiles.push(item)
  12325. this.showWarnIsDelete()
  12326. // this.showWarnIsDeleteFile(item, index + '', filePath)
  12327. })
  12328. Button() {
  12329. Image($r('app.media.share2'))
  12330. .fillColor(Color.White)
  12331. .width(20)
  12332. }
  12333. .width(40)
  12334. .height(40)
  12335. .type(ButtonType.Circle)
  12336. .backgroundColor(this.themeColor)
  12337. .margin(5)
  12338. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12339. .onClick(() => {
  12340. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  12341. })
  12342. }
  12343. }
  12344. /**
  12345. * 穿山甲banner广告
  12346. */
  12347. // private declare bannerAd: CSJNativeExpressAd;
  12348. // @State private status: string = "未加载"
  12349. // @State private isShowAd: boolean = false
  12350. // private declare mAdSlot: AdSlot;
  12351. // private mBiddingAdm = '' //服务端bidding才需要设置
  12352. // private expressLoadAdListener: NativeExpressAdListener = {
  12353. // /**
  12354. // * 加载失败的回调
  12355. // *
  12356. // * @param code
  12357. // * @param message
  12358. // */
  12359. // onError: (code: number, message: string) => {
  12360. // console.error("加载广告失败,code=" + code + ",message=" + message);
  12361. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  12362. // },
  12363. //
  12364. // /**
  12365. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  12366. // *
  12367. // * @param ads 返回的广告列表
  12368. // */
  12369. //
  12370. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  12371. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  12372. // if (ads && ads.length > 0) {
  12373. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  12374. // ad.setExpressInteractionListener({
  12375. // /**
  12376. // *广告的点击回调
  12377. // * @param type 广告的交互类型
  12378. // */
  12379. // onAdClicked: (type: number) => {
  12380. // console.log("BannerExpressAdPage==onAdClicked......");
  12381. // },
  12382. //
  12383. // /**
  12384. // * 广告的展示回调 每个广告仅回调一次
  12385. // * @param type 广告的交互类型
  12386. // */
  12387. // onAdShow: (type: number) => {
  12388. // console.log("BannerExpressAdPage==onAdShow......");
  12389. // },
  12390. //
  12391. // /**
  12392. // * 模板渲染失败
  12393. // */
  12394. // onRenderFail: (code: number, msg: string) => {
  12395. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  12396. // },
  12397. //
  12398. // /**
  12399. // * 模板渲染成功
  12400. // * @param width 返回view的宽 单位 vp
  12401. // * @param height 返回view的高 单位 vp
  12402. // */
  12403. // onRenderSuccess: (width: number, height: number) => {
  12404. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  12405. // this.bannerAd = ad;
  12406. // this.status = "广告加载完成待展示";
  12407. //
  12408. // this.showBannerAd()
  12409. // }
  12410. // })
  12411. // //渲染广告
  12412. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  12413. // this.setDislikeCallback(ad); //设置dislike
  12414. // ad.render(this.getUIContext())
  12415. // this.status = "广告加载中...";
  12416. // });
  12417. // }
  12418. // }
  12419. // }
  12420. //
  12421. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  12422. // ad.setDislikeCallback({
  12423. // /**
  12424. // * dislike show
  12425. // */
  12426. // onShow: () => {
  12427. // console.log("BannerExpressAdPage==dislike......show");
  12428. // },
  12429. //
  12430. // /**
  12431. // * @param position 选择的位置
  12432. // * @param value 选择的内容
  12433. // * @param enforceRemove 是否强制关闭广告
  12434. // */
  12435. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  12436. // this.isShowAd = false;
  12437. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  12438. // ",enforce=" + enforceRemove);
  12439. // },
  12440. //
  12441. // /**
  12442. // * 点击取消
  12443. // */
  12444. // onCancel: () => {
  12445. // console.log("BannerExpressAdPage==dislike......onCancel");
  12446. // }
  12447. //
  12448. // })
  12449. // }
  12450. /**
  12451. * 加载Banner广告
  12452. */
  12453. loadBannerAd(rit: string) {
  12454. // if (Utility.isNoble()) {
  12455. // return
  12456. // }
  12457. // if (!Utility.isPassInstallTime(2)) {
  12458. // return
  12459. // }
  12460. // this.isShowAd = false;
  12461. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  12462. // this.mAdSlot = new AdSlotBuilder()
  12463. // .setCodeId(rit)
  12464. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  12465. // .setAdCount(1)
  12466. // .setBidAdm(this.mBiddingAdm)
  12467. // .build()
  12468. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  12469. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  12470. // this.status = "广告加载中..."
  12471. }
  12472. /**
  12473. * 展示Banner广告
  12474. */
  12475. // showBannerAd() {
  12476. // if (!this.bannerAd) {
  12477. // return
  12478. // }
  12479. // this.isShowAd = true
  12480. // this.status = "已展示"
  12481. // }
  12482. /**
  12483. * 穿山甲广告代码结束
  12484. */
  12485. /**
  12486. * 处理歌单播放请求
  12487. */
  12488. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  12489. string, songFilePaths: string[], startIndex: number) {
  12490. try {
  12491. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  12492. // 检查是否为WebDAV播放请求
  12493. if (playlistId === 'webdav-playlist') {
  12494. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  12495. // 从全局内存读取videoItems数据
  12496. const videoItems = getWebdavVideoItems();
  12497. const currentPlayIndex = getWebdavCurrentPlayIndex();
  12498. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  12499. if (videoItems && videoItems.length > 0) {
  12500. // 验证webdav_account_id设置情况
  12501. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  12502. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  12503. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  12504. return
  12505. } else {
  12506. return
  12507. }
  12508. }
  12509. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  12510. const songMap: Map<number, VideoItem> = new Map()
  12511. let completedQueries = 0
  12512. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  12513. // 遍历所有文件路径,使用索引记录位置
  12514. for (let i = 0; i < songFilePaths.length; i++) {
  12515. const filePath = songFilePaths[i]
  12516. const index = i
  12517. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  12518. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  12519. const queryPromise = this.table.queryVideoByFilePath(filePath)
  12520. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  12521. queryPromise.then((videoItem) => {
  12522. completedQueries++
  12523. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  12524. if (videoItem) {
  12525. // 使用索引作为key保存到Map中,保持原始顺序
  12526. songMap.set(index, videoItem)
  12527. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  12528. } else {
  12529. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  12530. }
  12531. // 检查是否所有歌曲都已加载完成
  12532. if (completedQueries === songFilePaths.length) {
  12533. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  12534. // 按照索引顺序重建歌曲数组
  12535. const songs: VideoItem[] = []
  12536. for (let j = 0; j < songFilePaths.length; j++) {
  12537. const song = songMap.get(j)
  12538. if (song) {
  12539. songs.push(song)
  12540. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  12541. }
  12542. }
  12543. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  12544. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12545. }
  12546. }).catch((error: Error) => {
  12547. completedQueries++
  12548. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  12549. // 即使出错也要检查是否完成所有查询
  12550. if (completedQueries === songFilePaths.length) {
  12551. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  12552. // 按照索引顺序重建歌曲数组
  12553. const songs: VideoItem[] = []
  12554. for (let j = 0; j < songFilePaths.length; j++) {
  12555. const song = songMap.get(j)
  12556. if (song) {
  12557. songs.push(song)
  12558. }
  12559. }
  12560. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12561. }
  12562. })
  12563. }
  12564. } catch (error) {
  12565. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  12566. ToastUtil.showToast('播放失败')
  12567. }
  12568. }
  12569. /**
  12570. * 完成歌单加载并开始播放
  12571. */
  12572. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  12573. if (songs.length === 0) {
  12574. Logger.error('heanup 没有找到任何可播放的歌曲')
  12575. ToastUtil.showToast('没有找到可播放的歌曲')
  12576. return
  12577. }
  12578. this.songList = songs
  12579. this.sonDataSource.pushArrayData(songs)
  12580. this.sonDataSource.notifyDataReload()
  12581. this.curIndex = startIndex
  12582. if (songs[startIndex]) {
  12583. // 确保当前播放的歌曲也更新到存储
  12584. AppStorage.setOrCreate('currentSong', songs[startIndex])
  12585. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  12586. this.doPlay(songs[startIndex], startIndex, true)
  12587. }
  12588. PreferencesUtil.putSync('LastMusicList', this.songList)
  12589. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  12590. }
  12591. }
  12592. //视频气泡窗口的布局
  12593. @Builder
  12594. function customPopupBuilder(dataBu: BubbleBean) {
  12595. List() {
  12596. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  12597. ListItem() {
  12598. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12599. Row() {
  12600. Column() {
  12601. Image(dataBu.imageRes[index])
  12602. .height(28)
  12603. .fillColor(dataBu.color)
  12604. .alignSelf(ItemAlign.Center)
  12605. }
  12606. .width(32)
  12607. Text(item)
  12608. .padding({
  12609. top: 10,
  12610. bottom: 10,
  12611. right: 10,
  12612. left: 10
  12613. })
  12614. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  12615. .textAlign(TextAlign.Start)
  12616. .width("100%")
  12617. }
  12618. }
  12619. .backgroundColor($r('app.color.settings_background_main'))
  12620. .margin({ top: 6, bottom: 6 })
  12621. }
  12622. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12623. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  12624. TransitionEffect.scale({ x: 0, y: 0 })))
  12625. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12626. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12627. .onClick(() => {
  12628. dataBu.onItemClick?.(index)
  12629. })
  12630. })
  12631. }
  12632. .scrollBar(BarState.Off)
  12633. .width(120)
  12634. .divider({
  12635. strokeWidth: 1,
  12636. color: "#22FFFFFF"
  12637. })
  12638. }
  12639. // Function to calculate a hash for the file list
  12640. function simpleHash(fileList: string[]): string {
  12641. let hash = 0;
  12642. const str = fileList.join(',');
  12643. for (let i = 0; i < str.length; i++) {
  12644. const char = str.charCodeAt(i);
  12645. hash = (hash << 5) - hash + char;
  12646. hash |= 0; // Convert to 32bit integer
  12647. }
  12648. return hash.toString();
  12649. }
  12650. interface MoreItem {
  12651. id: number;
  12652. image: Resource;
  12653. title: string;
  12654. }
  12655. //视频气泡窗口的布局
  12656. @Builder
  12657. function cutPopupBuilder(dataBu: BubbleBean) {
  12658. Column() {
  12659. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  12660. .padding({
  12661. top: 10,
  12662. bottom: 10,
  12663. right: 10,
  12664. left: 10
  12665. })
  12666. .textAlign(TextAlign.Start)
  12667. .width(160)
  12668. .fontWeight(666)
  12669. .fontSize(16)
  12670. List() {
  12671. ForEach(dataBu.data, (item: string, index: number) => {
  12672. ListItem() {
  12673. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12674. Row() {
  12675. Column() {
  12676. Image($r('app.media.music_group'))
  12677. .height(28)
  12678. .fillColor(dataBu.color)
  12679. .alignSelf(ItemAlign.Center)
  12680. }
  12681. .width(32)
  12682. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  12683. .padding({
  12684. top: 10,
  12685. bottom: 10,
  12686. right: 10,
  12687. left: 10
  12688. })
  12689. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  12690. .fontSize(15)
  12691. }
  12692. }
  12693. .backgroundColor(Color.Transparent)
  12694. .margin({ top: 7, bottom: 7 })
  12695. }
  12696. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12697. .animation({ duration: 500 }),
  12698. TransitionEffect.scale({ x: 0, y: 0 })))
  12699. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12700. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12701. .onClick(() => {
  12702. dataBu.onItemClick?.(index)
  12703. })
  12704. })
  12705. }
  12706. .scrollBar(BarState.Off)
  12707. .width(150)
  12708. .divider({
  12709. strokeWidth: 1,
  12710. color: "#22FFFFFF"
  12711. })
  12712. }
  12713. .height(300)
  12714. .padding({
  12715. bottom: 30
  12716. })
  12717. }
  12718. function getFileDirName(filePath: string,rootPath:string): string{
  12719. if(filePath===rootPath){
  12720. return '首页'
  12721. }
  12722. let result = FileUtil.getFileName(filePath)
  12723. if(StrUtil.isEmpty(result))
  12724. return ''
  12725. if(result.startsWith('.'))
  12726. result = result.replace(/\./g, '')
  12727. return result
  12728. }
  12729. //只扫描当前目录下文件(不扫描子文件夹)的方法
  12730. @Concurrent
  12731. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  12732. const table: MediaTable = new MediaTable(context);
  12733. try {
  12734. // 直接获取当前目录下的文件列表
  12735. const files = FileUtil.listFileSync(dirPath);
  12736. await Promise.all(files.map(async (file) => {
  12737. const fPath = `${dirPath}/${file}`;
  12738. // 跳过目录,只处理文件
  12739. if (FileUtil.isDirectory(fPath)) {
  12740. return;
  12741. }
  12742. // 跳过特定格式文件
  12743. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  12744. return;
  12745. }
  12746. // 检查是否为媒体文件
  12747. if (Utility.isMeidaByExtension(fPath)) {
  12748. let mType = CommonConstants.TYPE_LOCAL;
  12749. if (fPath.includes(lockPath)) {
  12750. mType = CommonConstants.TYPE_LOCK;
  12751. }
  12752. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  12753. context, fPath, mType, true
  12754. );
  12755. table.insert(mediaItem, (id: number) => {
  12756. // 插入回调函数
  12757. }, cover_api);
  12758. }
  12759. }));
  12760. } catch (error) {
  12761. console.error(' 扫描当前目录失败:', error);
  12762. }
  12763. }