LocalMusic.ets 478 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751
  1. import TitleBar from './TitleBar'
  2. import { curves, display, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,borderRadiuses, SegmentButtonOptions } from '@kit.ArkUI';
  5. import {
  6. AppUtil,
  7. ArrayUtil,
  8. Base64Util,
  9. DateUtil,
  10. DeviceUtil,
  11. DisplayUtil,
  12. FileUtil,
  13. GlobalContext,
  14. ImageUtil,
  15. LogUtil,
  16. MD5,
  17. PreferencesUtil,
  18. RandomUtil,
  19. StrUtil,
  20. ToastUtil
  21. } from '@pura/harmony-utils';
  22. import { imagePathToPixelMap } from '../common/util/CommUtils';
  23. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  24. import { CommonConstants } from '../common/constants/CommonConstants';
  25. import { EventConstants } from '../common/constants/EventConstants';
  26. import Logger from '../common/util/Logger';
  27. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  28. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  29. import { BubbleBean } from '../viewmodel/BubbleBean';
  30. import { PopupPosition, XPopup } from '@chinalike/popup';
  31. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  32. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  33. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  34. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  35. import Base64 from '@ohos.util';
  36. import { Verify } from './Verify';
  37. import { taskpool } from '@kit.ArkTS';
  38. import { RotatingCover } from './RotatingCover';
  39. import { PlayConstants } from '../common/constants/PlayConstants';
  40. import { effectKit } from '@kit.ArkGraphics2D';
  41. import { ColorConversion } from '../common/util/ColorConversion';
  42. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  43. import { AvSessionController } from '../controller/AvSessionController';
  44. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  45. import { FFMpegTags,Utility } from '../common/util/Utility';
  46. import { TagsContentCover } from '../view/TagsContentCover';
  47. import { ImageFancyModifier } from '../common/util/AttributeModifierUtil'
  48. import {
  49. // DeviceChangeReason,
  50. IjkMediaPlayer,
  51. InterruptEvent,
  52. InterruptHintType,
  53. LogUtils,
  54. OnBufferingUpdateListener,
  55. OnCompletionListener,
  56. OnErrorListener,
  57. OnInfoListener,
  58. OnPreparedListener,
  59. OnSeekCompleteListener,
  60. OnTimedTextListener,
  61. OnVideoSizeChangedListener
  62. } from '@ohos/ijkplayer';
  63. import { PlayStatus } from '../common/PlayStatus';
  64. import fs from '@ohos.file.fs';
  65. import { image } from '@kit.ImageKit';
  66. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  67. import { UniversalDetector } from '@ohos/juniversalchardet';
  68. import { SettingPage } from '../pages/SettingPage';
  69. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  70. import { CommonConstants2 } from '../common/util/CommonConstants2';
  71. import { hilog } from '@kit.PerformanceAnalysisKit';
  72. import { LazyDataSource } from '../common/util/LazyDataSource';
  73. import MediaTable from '../common/util/MediaTable';
  74. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  75. import ImageUtils from '../common/util/ImageUtils';
  76. import { ringtone } from '@kit.RingtoneKit';
  77. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  78. import { resourceManager } from '@kit.LocalizationKit';
  79. import { deviceInfo } from '@kit.BasicServicesKit';
  80. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  81. import app from '@system.app';
  82. import { TextNodeController } from './PipLyricTextBuilder';
  83. import { IndexerView } from './IndexerView';
  84. import { KeyCode } from '@kit.InputKit';
  85. import { KnockController } from '../controller/KnockController';
  86. import { DeleteComptent } from '../view/DeleteComptent';
  87. import { ABLoopComptent } from '../view/ABLoopComptent';
  88. import { FixMessyView } from '../view/FixMessyView';
  89. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  90. import { CueComptent } from '../view/CueComptent';
  91. import PlaylistTable from '../common/util/PlaylistTable';
  92. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  93. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  94. import { convertPlaylistSongsToVideoItems, emptyView } from '../pages/PlaylistDetailPage';
  95. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  96. import { Song } from '../viewmodel/Song';
  97. import { SongType } from '../common/enums/SongType';
  98. import { WebdavManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  99. buildHttpHeadersWithWebDav,
  100. WebDavAuthItem} from '../common/util/WebdavManager';
  101. const TAG = 'LocalMusic';
  102. /**
  103. * 歌单播放事件数据
  104. */
  105. interface PlaylistEventData {
  106. playlistId: string;
  107. playlistName: string;
  108. songCount: number;
  109. startIndex: number;
  110. songFilePaths: string[];
  111. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  112. }
  113. const DEFAULT_INDEX =
  114. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  115. 'X', 'Y', 'Z']
  116. //排序类型
  117. function getTypeOrder(type: number) {
  118. switch (type) {
  119. case CommonConstants.TYPE_IS_DIR:
  120. return 1; // First
  121. case CommonConstants.TYPE_IS_CSJAD:
  122. return 2; // Middle
  123. case CommonConstants.TYPE_LOCAL:
  124. return 3; // Last
  125. default:
  126. return 4; // Unknown types, if any, go last
  127. }
  128. }
  129. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  130. // 定义接口
  131. interface HiCarAspectRatio {
  132. ratio: number;
  133. name: string;
  134. }
  135. interface GeneratedObjectLiteralInterface_1 {
  136. assetId: string;
  137. title: string;
  138. artist: string;
  139. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  140. mediaUri: string;
  141. // 该字段大写,音频'AUDIO',视频'VIDEO'
  142. mediaType: string;
  143. mediaSize: number;
  144. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  145. startPosition: number;
  146. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  147. duration: number;
  148. albumCoverUri: string;
  149. albumTitle: string;
  150. appName: string;
  151. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  152. drmScheme: string;
  153. }
  154. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  155. const ITEM_HEIGHT: number = 65; // 列表项中高度
  156. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  157. //功能强大的音乐播放器
  158. @Preview
  159. @Component
  160. export struct LocalMusic {
  161. @State offHeight: number = 75
  162. @State currentSongList: Array<VideoItem> = []//当前歌单
  163. @Consume currentSongListName:string //当前歌单名称
  164. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  165. @State isRefreshing: boolean = false;
  166. @State maxRefreshingHeight: number = 100.0;
  167. private contentNode?: ComponentContent<Object> = undefined;
  168. @State ratioL: number = 1;
  169. @State mediaKuCount: number = 0;
  170. @State albumCount: number = 0;
  171. @State artistCount: number = 0;
  172. @State fastForwardSeconds: string = '10'
  173. @State isShowBackFast: boolean = true//快进快退按钮
  174. @State isCanAuto:boolean = true
  175. @State opacityValueImage: number = 1;
  176. @State tipPopup:boolean = false
  177. @Consume mType: number;
  178. @StorageProp('themeColor') themeColor: string =
  179. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  180. themeMode: number = 0;
  181. @State titleName: string = '首页'
  182. @State textStr: string = ''
  183. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  184. // private download_path: string = '';
  185. @Consume rootPath: string //音频根目录
  186. @Consume currentPath: string
  187. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  188. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  189. @State lockPath: string = ''
  190. @State favPath: string = ''
  191. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  192. @State historyPath: string = ''
  193. @State historyList: Array<VideoItem> = []
  194. @Consume isHistory: boolean
  195. static readonly HISTORY_MUSIC: string = 'music_historyList';
  196. private table: MediaTable = new MediaTable(getContext(this))
  197. private playlistTable: PlaylistTable | null = null
  198. @State allPlaylists: Playlist[] = []
  199. @State isZero: boolean = false
  200. @State fileList: Array<string> = []
  201. @State dirList: Array<VideoItem> = []
  202. @Consume videoLocalList: Array<VideoItem>
  203. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  204. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  205. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  206. @State artistList: Array<VideoItem> = []; //艺术家文件
  207. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  208. @State albumList: Array<VideoItem> = []; //专辑文件
  209. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  210. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  211. @State imageOpacities: number[] = [];
  212. @Consume isCanBack: boolean
  213. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  214. @State showSingleLyric: boolean = false
  215. @State sortType: number = 4 //默认排序方式
  216. @State isShowSimi: boolean = false //是否显示私密音频
  217. @State isShowFAV: boolean = true //是否显示我的收藏
  218. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  219. @State isShowAllBar: boolean = true //是否显示播放全部条
  220. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  221. @State isShowHistory: boolean = true //是否显示最近播放
  222. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  223. @State isGridMusic: boolean = false //是否网格布局
  224. @State isCircleBtn: boolean = false //是否圆形播放按钮
  225. @State twoFingerType: number = 3 //双支放大缩小的类型
  226. @State isScrollHide: boolean = false //是否滚动隐藏
  227. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  228. @State isStartAutoPlay: boolean = false //启动后自动播放
  229. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  230. @State isShowHeader: boolean = true
  231. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  232. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  233. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  234. @State isSwipe: boolean = false //listItem的左滑开关
  235. @State openSkipSongAnimate: boolean = true//切歌动画效果
  236. @State customizeBgPath: string | undefined = '';
  237. @State isDarkMode: boolean = false
  238. @State lyricTextWeight: number = 400
  239. @State lyricTextWeightPip: number = 400
  240. @State currentSwiperIndex: number = 0
  241. @State blurValue: number = 0 //背景模糊
  242. @State bgBrightness: number = 0 //背景亮度
  243. private listScroller: ListScroller = new ListScroller()
  244. private playListScroller: Scroller = new Scroller()
  245. @State isOneKeyTags:boolean = false
  246. @State isFixMessy:boolean = false
  247. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  248. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  249. @StorageProp('bottomRectHeight') bottomRectHeight: number = 0;
  250. @StorageProp('windowWidth') windowWidth: number = 0;
  251. @StorageProp('windowHeight') windowHeight: number = 0;
  252. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  253. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  254. private UNKONWN:string = '';
  255. private listArea: Area = {
  256. width: 0,
  257. height: 0,
  258. position: {},
  259. globalPosition: {}
  260. }
  261. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  262. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  263. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  264. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  265. //瀑布流的列数横竖屏动态切换
  266. onIsLandscapeChange() {
  267. if(this.isLandscape){
  268. this.columns = 4
  269. }else{
  270. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  271. }
  272. }
  273. onColorModeChange() {
  274. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  275. if (this.isCustomizeBg) {
  276. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  277. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  278. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  279. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  280. this.tabOptions.selectedBackgroundColor = Color.Transparent
  281. } else {
  282. if (!this.isDarkMode) {
  283. this.titleBarModel.setTitleBarBackground(this.themeColor)
  284. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  285. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  286. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  287. this.tabOptions.selectedBackgroundColor = this.themeColor
  288. } else {
  289. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  290. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  291. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  292. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  293. this.tabOptions.selectedBackgroundColor = $r('app.color.silvery')
  294. }
  295. }
  296. }
  297. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  298. onTopBarhange(){
  299. if(this.isShowTitleBar){
  300. console.log('onecold 导航条显示')
  301. this.topBarHeight = 50
  302. this.offHeight = 75
  303. }else{
  304. console.log('onecold 导航条隐藏')
  305. this.topBarHeight = 0
  306. if(this.twoFingerType!=4){
  307. this.offHeight = 30
  308. }
  309. }
  310. }
  311. //点击某个歌单id发生变化的时候回调
  312. onIDChange(){
  313. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  314. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  315. if(this.modeType==4){
  316. this.isShowTitleBar = false
  317. this.titleBarModel.setTitleName(this.currentSongListName)
  318. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  319. //获取缓存
  320. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  321. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  322. if(StrUtil.isNotEmpty(cacheSongs)){
  323. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  324. this.updateListData(this.currentSongList, true)
  325. }
  326. this.doSongListTask()//获取歌单信息
  327. }
  328. }
  329. async doSongListTask() {
  330. // 初始化歌单数据库
  331. const playlistTable = new PlaylistTable(this.context);
  332. // 查询歌单中的所有歌曲
  333. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  334. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  335. if (ArrayUtil.isEmpty(playlistSongs)) {
  336. this.updateListData([], true)
  337. } else {
  338. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  339. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  340. this.updateListData(this.currentSongList, true)
  341. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  342. // 只保存前100条记录到缓存中
  343. let canceList = this.currentSongList.slice(0, 100);
  344. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  345. JSON.stringify(canceList))
  346. } else {
  347. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  348. }
  349. }
  350. }
  351. onModeChange() {
  352. this.isFavMusic = false
  353. if (this.modeType === 2 || this.modeType === 3|| this.modeType === 4) {
  354. this.titleBarModel.setRightIcon(null)
  355. } else {
  356. this.titleBarModel.setRightIcon(($r('app.media.add')))
  357. }
  358. LogUtil.info('onecold onModeChange = ' + this.modeType)
  359. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  360. switch (this.modeType) {
  361. case 0:
  362. this.getSortedFiles(this.currentPath)
  363. break
  364. case 1:
  365. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  366. this.updateListData(this.mediaKuList)
  367. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  368. break
  369. case 2:
  370. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  371. this.updateListData(this.artistList)
  372. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  373. break
  374. case 3:
  375. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  376. this.updateListData(this.albumList)
  377. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  378. break
  379. }
  380. }
  381. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  382. // @StorageLink('isPlay') isPlay: boolean = false;
  383. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  384. @StorageLink('songList') songList: Array<VideoItem> = [];
  385. @State translateY: number = 0;
  386. @State isShowSheet: boolean = false;
  387. @State isShowSheetView: boolean = false;
  388. @State isShowTimeCloseView: boolean = false;
  389. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  390. @StorageLink('currIndex') curIndex: number = 0;
  391. @Consume isShowDrawer: boolean;
  392. @Consume offsetX: number;
  393. @State isFac: boolean = false;
  394. @State favList: Array<VideoItem> = []
  395. @Consume isFavMusic: boolean
  396. @State isClickedPLayAll: boolean = false;
  397. private scrollerForlist: ListScroller = new ListScroller();
  398. private knockController: KnockController | undefined = undefined;
  399. imagesF: ImageFrameInfo[] = [
  400. { src: $r("app.media.app_loading0") },
  401. { src: $r("app.media.app_loading1") },
  402. { src: $r("app.media.app_loading2") },
  403. { src: $r("app.media.app_loading3") },
  404. ]
  405. @State animationState: AnimationStatus = AnimationStatus.Initial
  406. // 缓存机制
  407. private cache: Map<string, Array<VideoItem>> = new Map();
  408. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  409. // 持久化缓存
  410. private async saveCacheToStorage() {
  411. const cacheArray = Array.from(this.cache.entries());
  412. const stringCacheArray = Array.from(this.stringCache.entries());
  413. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  414. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  415. }
  416. // 载入缓存
  417. private async loadCacheFromStorage() {
  418. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  419. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  420. if (cacheString) {
  421. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  422. this.cache = new Map(cacheArray);
  423. }
  424. if (stringCacheString) {
  425. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  426. this.stringCache = new Map(stringCacheArray);
  427. }
  428. }
  429. // 查找缓存
  430. private findCache(key: string): Array<VideoItem> | undefined {
  431. return this.cache.get(key);
  432. }
  433. // 查找字符串缓存
  434. private findStringCache(key: string): string | undefined {
  435. return this.stringCache.get(key);
  436. }
  437. // 添加缓存
  438. private addCache(key: string, value: Array<VideoItem>) {
  439. this.cache.set(key, value);
  440. }
  441. // 添加字符串缓存
  442. private addStringCache(key: string, value: string) {
  443. this.stringCache.set(key, value);
  444. }
  445. // 删除缓存
  446. private deleteCache(key: string) {
  447. this.cache.delete(key);
  448. this.saveCacheToStorage()
  449. }
  450. // 删除字符串缓存
  451. private deleteStringCache(key: string) {
  452. this.stringCache.delete(key);
  453. }
  454. // 多选机制
  455. @State selectedFiles: Array<VideoItem> = [];
  456. @State isMultiSelect: boolean = false;
  457. @State isAllSelected: boolean = false;
  458. @State appName: string = ''
  459. @State isHasDir: boolean = false
  460. @State packName: string = ''
  461. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  462. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  463. .setTitleTextStyle(FontStyle.Normal)
  464. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  465. .setLeftIcon($r('app.media.menu'))
  466. .setLeftIconWidth(26)
  467. .setLeftIconHeight(26)
  468. .setTitleName('首页')
  469. .setTitleBarMinHeight(55)
  470. .setTitleFontSize(18)
  471. .setTitleFontColor(Color.White)
  472. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  473. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  474. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  475. .setRightIcon($r('app.media.add'))
  476. .setOnRightClickListener(() => {
  477. this.showSheelDialog()
  478. })
  479. // .setOnTitleClickListener(() => {
  480. // this.showPupDialog()
  481. // })
  482. .setOnLeftClickListener(() => {
  483. this.doSwipBack()
  484. })
  485. doSwipBack() {
  486. this.isZero = false
  487. if (this.modeType !== 0 && this.isCanBack) {
  488. this.onModeChange()
  489. this.isCanBack = false
  490. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  491. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  492. setTimeout(() => {
  493. if (this.modeType == 2) {
  494. if (this.isGridMusic||this.twoFingerType==4) {
  495. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  496. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  497. if(this.twoFingerType==4){
  498. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  499. }else{
  500. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  501. }
  502. } else {
  503. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  504. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  505. }
  506. } else if (this.modeType == 3) {
  507. if (this.isGridMusic||this.twoFingerType==4) {
  508. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  509. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  510. if(this.twoFingerType==4){
  511. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  512. }else{
  513. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  514. }
  515. } else {
  516. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  517. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  518. }
  519. }
  520. }, 200)
  521. return
  522. }
  523. if (this.isHistory || this.isFavMusic) {
  524. this.isHistory = false
  525. this.getSortedFiles(this.currentPath)
  526. return
  527. }
  528. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  529. animateTo({ duration: 555 }, () => {
  530. // 动画闭包内控制Image组件的出现和消失
  531. this.isShowDrawer = !this.isShowDrawer
  532. this.offsetX = 0
  533. })
  534. return
  535. }
  536. //返回上一级歌单的滚动位置
  537. setTimeout(() => {
  538. if (this.modeType == 0) {
  539. if (this.isGridMusic||this.twoFingerType==4) {
  540. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  541. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  542. if(this.twoFingerType==4){
  543. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  544. }else{
  545. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  546. }
  547. } else {
  548. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  549. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  550. }
  551. }
  552. }, 300)
  553. this.currentPath = Utility.getParentDirectory(this.currentPath)
  554. Logger.info('this.currentPath2 = ' + this.currentPath)
  555. this.getSortedFiles(this.currentPath)
  556. }
  557. // 组件生命周期
  558. aboutToAppear() {
  559. // 初始化 PlaylistTable
  560. this.playlistTable = new PlaylistTable(getContext(this))
  561. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  562. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  563. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  564. this.tipPopup = !this.tipPopup
  565. PreferencesUtil.putSync('isFirstTiped',false)
  566. }
  567. this.initSetting()
  568. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  569. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  570. Utility.getAppName(getContext(this)).then((appName: string) => {
  571. this.appName = appName
  572. })
  573. this.packName = AppUtil.getBundleName()
  574. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  575. this.loadCacheFromStorage(); // 加载文件夹缓存
  576. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  577. this.initLoadCache()
  578. this.mkDownLoadDir()
  579. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  580. // 监听广播事件(打开其他应用处理)
  581. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  582. this.saveVideoDatas([eventData.data?.message], true)
  583. });
  584. //侧滑广播接收时间
  585. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  586. // 监听广播事件(打开其他应用处理)
  587. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  588. animateTo({ duration: 555 }, () => {
  589. this.doSwipBack()
  590. })
  591. });
  592. //ScanFilePage广播接收时间
  593. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  594. // 监听ScanFilePage广播事件(更新数据库)
  595. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  596. this.doUpdateData()
  597. });
  598. // 监听歌单播放请求事件
  599. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  600. emitter.on(eventPlaylistPlay, (eventData: emitter.EventData) => {
  601. Logger.info('heanup eventPlaylistPlay received - full eventData: ' + JSON.stringify(eventData))
  602. Logger.info('heanup eventPlaylistPlay received - eventData.data: ' + JSON.stringify(eventData.data))
  603. const data = eventData.data as Record<string, Object>
  604. if (!data) {
  605. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  606. return
  607. }
  608. // 检查歌单播放数据结构
  609. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  610. Logger.info('heanup eventPlaylistPlay: 接收到歌单播放数据')
  611. // 提取WebDAV认证信息(如果存在)
  612. let webDavAuthInfo: WebDavAuthItem | undefined = undefined;
  613. if (data.webDavAuthInfo) {
  614. // 将webDavAuthInfo转换为正确的类型
  615. const authData = data.webDavAuthInfo as Record<string, Object>;
  616. webDavAuthInfo = {
  617. accountId: authData.accountId as number,
  618. host: authData.host as string,
  619. port: authData.port as number,
  620. account: authData.account as string,
  621. password: authData.password as string,
  622. enableHttps: authData.enableHttps as boolean
  623. };
  624. Logger.info(`heanup 从事件中获取到WebDAV认证信息,账户ID: ${webDavAuthInfo.accountId}`);
  625. }
  626. // 手动构建数据对象以避免类型转换问题
  627. const playlistData: PlaylistEventData = {
  628. playlistId: data.playlistId as string,
  629. playlistName: data.playlistName as string,
  630. songCount: data.songCount as number,
  631. startIndex: data.startIndex as number,
  632. songFilePaths: data.songFilePaths as string[]
  633. }
  634. // 根据文件路径重新构建歌曲列表,并传递WebDAV认证信息
  635. this.handlePlaylistPlayRequest(
  636. playlistData.playlistId,
  637. playlistData.playlistName,
  638. playlistData.songFilePaths,
  639. playlistData.startIndex,
  640. webDavAuthInfo
  641. )
  642. return
  643. }
  644. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  645. });
  646. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  647. // 监听广播事件(通用设置配置更新)
  648. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  649. this.doChangeSetting()
  650. });
  651. let event: Callback<InterruptEvent> = (event) => {
  652. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  653. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  654. this.savePlaybackPosition()
  655. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  656. this.pause();
  657. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  658. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  659. console.info('onecold startPlayOrResumePlay 514')
  660. this.startPlayOrResumePlay();
  661. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  662. this.stop();
  663. }
  664. }
  665. this.mIjkMediaPlayer.on('audioInterrupt', event);
  666. // 音频设备断连回调处理
  667. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  668. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  669. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  670. // this.pause();
  671. // }
  672. // }
  673. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  674. this.makeWorker()
  675. //折叠屏的屏幕显示模式变化
  676. display.on('foldDisplayModeChange', (data) => {
  677. this.doChangeBarHeight()
  678. });
  679. display.on('foldStatusChange', (data) => {
  680. Logger.info('onecold foldStatusChange ')
  681. });
  682. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  683. // 读取 themeMode 并同步 currentColorMode
  684. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  685. this.applyThemeMode(this.themeMode)
  686. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  687. AppStorage.setOrCreate('themeColor', themeColor);
  688. this.themeColor = themeColor;
  689. this.doChangeSetting()
  690. this.windowClass.on('windowSizeChange', (size) => {
  691. LogUtil.info('onecold windowSizeChange')
  692. this.doChangeBarHeight()
  693. let viewWidth = px2vp(size.width);
  694. let viewHeight = px2vp(size.height);
  695. if(this.isPhoneLan()){
  696. this.is_auto_hide_progress = false
  697. if(this.isHiCar()){
  698. return
  699. }
  700. setTimeout(() => {
  701. this.is_auto_hide_progress = true
  702. }, 6000)
  703. }else{
  704. this.startAutoHide()
  705. }
  706. });
  707. this.eventHub.on('onStateChange', (fg: boolean) => {
  708. if (fg && this.curState === 'STARTED') {
  709. this.stopPip();
  710. }
  711. });
  712. }
  713. //载入媒体库,艺术家,专辑等缓存
  714. initLoadCache(){
  715. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  716. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  717. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  718. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  719. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  720. if(ArrayUtil.isNotEmpty(cachedList)){
  721. this.mediaKuList = cachedList
  722. if(this.modeType==1){
  723. this.updateListData(this.mediaKuList)
  724. }
  725. }
  726. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  727. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  728. if(ArrayUtil.isNotEmpty(artistCachedList)){
  729. this.artistList = artistCachedList
  730. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  731. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  732. this.artistMap = new Map(parsedArray);
  733. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  734. if(this.modeType==2){
  735. this.updateListData(this.artistList)
  736. }
  737. }
  738. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  739. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  740. if(ArrayUtil.isNotEmpty(albumCachedList)){
  741. this.albumList = albumCachedList
  742. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  743. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  744. this.albumMap = new Map(parsedArray);
  745. if(this.modeType==3){
  746. this.updateListData(this.albumList)
  747. }
  748. }
  749. }
  750. startAutoHide() {
  751. if(this.isHiCar()){
  752. return
  753. }
  754. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  755. console.info('onecold startAutoHide')
  756. this.is_auto_hide_progress = false
  757. setTimeout(() => {
  758. this.is_auto_hide_progress = true
  759. }, 6000)
  760. }
  761. }
  762. applyThemeMode(mode: number) {
  763. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  764. if (mode === 1) {
  765. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  766. } else if (mode === 2) {
  767. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  768. }
  769. AppStorage.setOrCreate('currentColorMode', colorMode)
  770. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  771. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  772. AppStorage.setOrCreate('themeMode', mode)
  773. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  774. // 只有强制浅色/深色时才主动设置
  775. const context = getContext(this) as common.UIAbilityContext
  776. context.getApplicationContext().setColorMode(colorMode)
  777. }
  778. initSetting() {
  779. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  780. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  781. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  782. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  783. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  784. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  785. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  786. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  787. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  788. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  789. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  790. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  791. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  792. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  793. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  794. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  795. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  796. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  797. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  798. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  799. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  800. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  801. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  802. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  803. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  804. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  805. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  806. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  807. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  808. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  809. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  810. if(this.volumeSmall){
  811. this.volume = 0.5
  812. }else{
  813. this.volume = 1
  814. }
  815. //如果是hicar连接状态,这些都是false
  816. if(this.isHiCar()){
  817. this.isShowTitleBar = false//不显示导航栏
  818. this.columns=4
  819. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  820. {
  821. this.isShowHeader = false//二级菜单不显示头部
  822. this.isGridMusic= false//用list不用网格
  823. this.isCoverTopBig = false
  824. }
  825. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  826. }
  827. if (this.isSavePlayMode) {
  828. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  829. }
  830. if (this.isCustomizeBg) {
  831. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  832. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  833. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  834. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  835. } else {
  836. if (!this.isDarkMode) {
  837. this.titleBarModel.setTitleBarBackground(this.themeColor)
  838. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  839. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  840. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  841. } else {
  842. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  843. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  844. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  845. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  846. }
  847. }
  848. }
  849. doChangeSetting() {
  850. this.initSetting()
  851. this.deleteCache(this.currentPath)
  852. if (this.modeType === 0) {
  853. this.getSortedFiles(this.currentPath)
  854. }
  855. }
  856. doChangeBarHeight() {
  857. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  858. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  859. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  860. this.setBarHeightNormal()
  861. }
  862. }
  863. onPageShow() {
  864. this.knockController?.immersiveListening();
  865. app.setImageCacheCount(100);
  866. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  867. app.setImageRawDataCacheSize(104857600);
  868. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  869. }
  870. //开启线程查看各个数据库
  871. makeWorker() {
  872. setTimeout(() => {
  873. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  874. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  875. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  876. // workerInstance.postMessage({
  877. // code: 1,
  878. // data1: this.context,
  879. // data2: this.rootPath,
  880. // data3: this.lockPath,
  881. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  882. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  883. // });
  884. PreferencesUtil.putSync('isFirstApp', false)
  885. } else {
  886. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  887. workerInstance.postMessage({ code: 3, data: this.context });
  888. workerInstance.postMessage({ code: 4, data: this.context });
  889. this.getHistoryList(false)
  890. }
  891. }, 1000)
  892. workerInstance.onmessage = (e: MessageEvents): void => {
  893. switch (e.data.code) {
  894. case 101: //第一次扫描文件夹入库
  895. ToastUtil.showToast('刷新同步数据库成功!')
  896. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  897. this.doUpdateData()
  898. break;
  899. case 102: //查询媒体库列表
  900. this.isRefreshing = false
  901. this.mediaKuList = e.data.data
  902. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  903. Utility.doSortListAscending(this.mediaKuList)
  904. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  905. if (this.modeType === 1) {
  906. this.updateListData(this.mediaKuList)
  907. }
  908. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  909. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  910. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  911. // 只保存前100条记录到缓存中
  912. let truncatedList = this.mediaKuList.slice(0, 100);
  913. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  914. } else {
  915. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  916. }
  917. break;
  918. case 103: //收到查询艺术家列表
  919. this.isRefreshing = false
  920. this.artistMap = e.data.data1;
  921. this.artistList = e.data.data2;
  922. PreferencesUtil.putSync('artistCount', this.artistList.length)
  923. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  924. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  925. // 只保存前100条记录到缓存中
  926. let truncatedList = this.artistList.slice(0, 100);
  927. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  928. } else {
  929. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  930. }
  931. // 处理并缓存前60条艺术家数据
  932. const sortedEntries = Array.from(this.artistMap.entries())
  933. .sort((a, b) => b[1].length - a[1].length)
  934. .slice(0, 60);
  935. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  936. break;
  937. case 104: //收到查询专辑列表
  938. this.isRefreshing = false
  939. this.albumMap = e.data.data1;
  940. this.albumList = e.data.data2
  941. //查询完毕在启动是否自动播放
  942. if (this.isStartAutoPlay&&this.isCanAuto) {
  943. this.isCanAuto = false
  944. console.info('onecold startPlayOrResumePlay 757')
  945. this.startPlayOrResumePlay()
  946. }
  947. PreferencesUtil.putSync('albumCount', this.albumList.length)
  948. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  949. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  950. // 只保存前100条记录到缓存中
  951. let truncatedList = this.albumList.slice(0, 100);
  952. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  953. } else {
  954. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  955. }
  956. const mapArrayAlbum = Array.from(this.albumMap.entries())
  957. .sort((a, b) => b[1].length - a[1].length)
  958. .slice(0, 60);
  959. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  960. break;
  961. }
  962. };
  963. // 在调用terminate后,执行onexit
  964. workerInstance.onexit = (code) => {
  965. console.log("main thread terminate");
  966. }
  967. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  968. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  969. workerInstance.onerror = (err: ErrorEvent) => {
  970. console.log("onerror" + err.message);
  971. }
  972. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  973. //碰一碰分享的监听
  974. this.knockController = KnockController.getInstance(this.context);
  975. this.knockController?.immersiveListening();
  976. }
  977. onPageHide(): void {
  978. this.knockController?.immersiveDisableListening();
  979. }
  980. @State isFirstStartPlay: boolean = false
  981. //获取download_path
  982. async mkDownLoadDir() {
  983. const documentViewPicker = new picker.DocumentViewPicker()
  984. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  985. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  986. this.currentPath = this.rootPath
  987. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  988. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  989. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  990. Logger.info('onecold rootPath = ' + this.rootPath)
  991. Logger.info('onecold lockPath = ' + this.lockPath)
  992. if (!FileUtil.accessSync(this.lockPath)) {
  993. FileUtil.mkdirSync(this.lockPath)
  994. }
  995. if (!FileUtil.accessSync(this.favPath)) {
  996. FileUtil.mkdirSync(this.favPath)
  997. }
  998. if (!FileUtil.accessSync(this.historyPath)) {
  999. FileUtil.mkdirSync(this.historyPath)
  1000. }
  1001. this.getSortedFiles(this.rootPath).then(() => {
  1002. this.isFavMusic = false
  1003. //穿山甲
  1004. // this.loadBannerAd(CSJUtil.getBannerID())
  1005. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1006. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1007. if (ArrayUtil.isEmpty(this.songList)) {
  1008. this.songList = this.getCurFileList()
  1009. } else {
  1010. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1011. }
  1012. if (ArrayUtil.isNotEmpty(this.songList)) {
  1013. this.isFirstStartPlay = true
  1014. this.sonDataSource.pushArrayData(this.songList)
  1015. if (this.currentSong === undefined) {
  1016. this.isFirstStartPlay = false
  1017. this.currentSong = this.songList[0]
  1018. }
  1019. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  1020. this.name = this.currentSong.name
  1021. this.cover = this.currentSong.pixelMapPath
  1022. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1023. } else {
  1024. this.name = '空空如也'
  1025. }
  1026. })
  1027. this.getFavList(false)
  1028. }
  1029. getFavList(isFavRefresh: boolean) {
  1030. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1031. this.favList = result
  1032. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1033. this.videoLocalList = this.favList
  1034. this.updateListData(this.videoLocalList)
  1035. }
  1036. })
  1037. }
  1038. getHistoryList(isRefresh: boolean) {
  1039. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1040. this.historyList = result
  1041. // for (let i = 0; i < this.historyList.length; i++) {
  1042. //
  1043. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1044. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1045. // }
  1046. if (isRefresh) {
  1047. this.videoLocalList = this.historyList
  1048. this.updateListData(this.videoLocalList, true)
  1049. }
  1050. })
  1051. }
  1052. // 组件消失生命周期
  1053. aboutToDisappear() {
  1054. console.info('LifeCycleComponent aboutToDisappear');
  1055. this.knockController?.immersiveDisableListening();
  1056. this.curIndex = 0
  1057. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1058. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1059. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1060. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1061. this.mDestroyPage = true;
  1062. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1063. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1064. this.stop();
  1065. }
  1066. this.mIjkMediaPlayer.off('audioInterrupt');
  1067. if (workerInstance) {
  1068. workerInstance.terminate();
  1069. }
  1070. this.stopPip();
  1071. this.destroyPipController()
  1072. }
  1073. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  1074. this.isFavMusic = false
  1075. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1076. if (isWorkerPost) {
  1077. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1078. }
  1079. if (this.modeType !== 0) {
  1080. this.openMusic(isOpen, destPath)
  1081. return
  1082. }
  1083. console.info('onecold getSortedFiles 2')
  1084. this.isCanBack = false
  1085. this.currentPath = curPath
  1086. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1087. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  1088. if (curPath === this.rootPath) {
  1089. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1090. } else {
  1091. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1092. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1093. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  1094. }
  1095. }
  1096. // Get the current file list and calculate its hash
  1097. this.fileList = FileUtil.listFileSync(curPath);
  1098. const currentHash = simpleHash(this.fileList);
  1099. // Check cache
  1100. const cachedValue = this.findCache(curPath);
  1101. Logger.info('onecold cachedValue = ' + cachedValue)
  1102. const cachedHash = this.findStringCache(curPath + '_hash');
  1103. const cachedDirList = this.findCache(curPath + "_dirList");
  1104. if (cachedValue !== undefined) {
  1105. // this.videoLocalList = cachedValue;
  1106. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1107. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1108. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1109. }
  1110. this.updateListData(cachedValue)
  1111. }
  1112. if (cachedDirList !== undefined) {
  1113. this.dirList = cachedDirList
  1114. }
  1115. //通过当前hash值和缓存hash判断list有没有变化
  1116. if (cachedValue && cachedHash === currentHash) {
  1117. return;
  1118. }
  1119. this.fileList = FileUtil.listFileSync(curPath)
  1120. let directories: Array<VideoItem> = [];
  1121. let files: Array<VideoItem> = [];
  1122. for (let i = 0; i < this.fileList.length; i++) {
  1123. console.info(`The name of file: ${this.fileList[i]}`);
  1124. let path = curPath + '/' + this.fileList[i]
  1125. if (FileUtil.isDirectory(path)) {
  1126. let item: VideoItem =
  1127. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1128. '')
  1129. if (this.isShowDir(item.name)) {
  1130. directories.push(item);
  1131. }
  1132. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1133. // Utility.doSortListAscending(directories)
  1134. } else {
  1135. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1136. let item: VideoItem =
  1137. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1138. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1139. files.push(item);
  1140. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1141. // this.doSortListAscending(files)
  1142. }
  1143. }
  1144. }
  1145. }
  1146. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1147. if (this.currentPath !== this.lockPath) {
  1148. files = result;
  1149. }
  1150. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1151. Utility.doSortListAscending(files)
  1152. if (this.currentPath === this.rootPath) {
  1153. this.dirList = directories
  1154. this.addCache(curPath + "_dirList", this.dirList);
  1155. }
  1156. //插入广告先注释掉
  1157. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1158. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1159. // directories.push(adItem)
  1160. // }
  1161. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1162. this.videoLocalList = directories.concat(files);
  1163. this.updateListData(this.videoLocalList)
  1164. if (ArrayUtil.isNotEmpty(files)) {
  1165. if (this.currentPath != this.rootPath) {
  1166. if (files) {
  1167. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1168. }
  1169. }
  1170. // 缓存结果
  1171. this.addCache(curPath, this.videoLocalList);
  1172. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1173. this.addStringCache(curPath + '_hash', currentHash);
  1174. }
  1175. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1176. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1177. //
  1178. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1179. //
  1180. // }
  1181. // this.setButtonStatus()
  1182. this.openMusic(isOpen, destPath)
  1183. });
  1184. }
  1185. //第三方app打开天天静听导入音乐后播放
  1186. openMusic(isOpen?: boolean, destPath?: string){
  1187. if (isOpen&&destPath) {
  1188. if (destPath === undefined) {
  1189. // 处理 destPath 为 undefined 的情况
  1190. return
  1191. }
  1192. if (destPath.endsWith('.lrc')) {
  1193. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1194. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1195. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1196. this.initLyric(lyricPath);
  1197. }
  1198. return
  1199. }
  1200. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  1201. this.doPlay(item2,0,false,true)
  1202. this.isShowPlay = true
  1203. }
  1204. }
  1205. //扫描文件夹入库
  1206. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1207. const files = FileUtil.listFileSync(curPath);
  1208. let mediaItems: VideoItem[] = [];
  1209. Logger.info('onecold scanDirectory start ')
  1210. for (const file of files) {
  1211. const fPath = `${curPath}/${file}`;
  1212. if (fPath === this.lockPath) {
  1213. Logger.info(`Skipping locked path: ${fPath}`);
  1214. continue;
  1215. }
  1216. if (FileUtil.isDirectory(fPath)) {
  1217. // Recursively scan subdirectories
  1218. const subDirItems = await this.scanDirectory(fPath);
  1219. mediaItems = mediaItems.concat(subDirItems);
  1220. } else {
  1221. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1222. // Process media files
  1223. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1224. let mediaItem: VideoItem =
  1225. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1226. mediaItems.push(mediaItem);
  1227. this.table.insert(mediaItem, (id: number) => {
  1228. });
  1229. }
  1230. }
  1231. }
  1232. return mediaItems;
  1233. }
  1234. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1235. animateTo({ duration: 666 }, () => {
  1236. this.opacityItem = 0;
  1237. });
  1238. setTimeout(() => {
  1239. this.videoLocalList = mList;
  1240. if (!noSort) {
  1241. if (this.modeType === 0 || this.modeType === 1) {
  1242. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1243. this.doSortType(this.sortType)
  1244. }
  1245. }
  1246. this.dataSource.pushArrayData(this.videoLocalList)
  1247. animateTo({ duration: 666 }, () => {
  1248. this.opacityItem = 1;
  1249. });
  1250. this.setButtonStatus()
  1251. }, 200);
  1252. }
  1253. //排序模式和多选模式
  1254. showPupDialog() {
  1255. if (this.modeType === 2 || this.modeType === 3) {
  1256. this.titleBarModel.setRightIcon(null)
  1257. } else {
  1258. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1259. }
  1260. let dataBean = new BubbleBean()
  1261. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1262. dataBean.color = this.themeColor
  1263. dataBean.modeType = this.modeType
  1264. dataBean.imageRes =
  1265. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1266. $r('app.media.refresh')]
  1267. let pup: XPopup;
  1268. if (this.isDarkMode) {
  1269. pup = XPopup.Builder()
  1270. .setPopupPosition(PopupPosition.BOTTOM)
  1271. .atView('pup_positon_music')
  1272. .setBackgroundColor(Color.Black)
  1273. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1274. .show()
  1275. } else {
  1276. pup = XPopup.Builder()
  1277. .setPopupPosition(PopupPosition.BOTTOM)
  1278. .atView('pup_positon_music')
  1279. .setBackgroundColor(Color.White)
  1280. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1281. .show()
  1282. }
  1283. dataBean.onItemClick = (i) => {
  1284. XPopup.dismissTop()
  1285. switch (i) {
  1286. case 0: //首页
  1287. this.modeType = 0
  1288. this.getSortedFiles(this.currentPath)
  1289. break
  1290. case 1:
  1291. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1292. this.modeType = 1
  1293. this.updateListData(this.mediaKuList)
  1294. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1295. break
  1296. case 2:
  1297. this.modeType = 2
  1298. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1299. this.updateListData(this.artistList)
  1300. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1301. break
  1302. case 3:
  1303. this.modeType = 3
  1304. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1305. this.updateListData(this.albumList)
  1306. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1307. break
  1308. case 4: //同步数据
  1309. // this.asyncCurrentPathData()
  1310. break
  1311. }
  1312. }
  1313. }
  1314. getCurFileList(): Array<VideoItem> {
  1315. if(this.isSearchMode){
  1316. return this.filteredList
  1317. }
  1318. let files: Array<VideoItem> = [];
  1319. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1320. for (let i = 0; i < this.videoLocalList.length; i++) {
  1321. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1322. files.push(this.videoLocalList[i]);
  1323. }
  1324. }
  1325. }
  1326. return files
  1327. }
  1328. setButtonStatus() {
  1329. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1330. this.isZero = false
  1331. } else {
  1332. this.isZero = true
  1333. }
  1334. if (this.currentPath !== this.rootPath &&
  1335. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1336. this.isHasDir = true //不为空,说明有子文件夹
  1337. } else {
  1338. this.isHasDir = false
  1339. }
  1340. }
  1341. showRankDialog() {
  1342. if ((this.modeType === 2&&!this.isCanBack) || (this.modeType === 3&&!this.isCanBack)) {
  1343. //动作面板
  1344. DialogHelper.showBottomSheetDialog({
  1345. title: "请选择排序模式",
  1346. maskColor: Color.Transparent,
  1347. // sheets: ["按名称升序", "按名称降序"],
  1348. sheets: [
  1349. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1350. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1351. { value: '按数量升序', fontColor: $r('app.color.text_color') },
  1352. { value: '按数量降序', fontColor: $r('app.color.text_color') },
  1353. ],
  1354. backgroundColor: $r('app.color.bg_card'),
  1355. height: '45%',
  1356. transition: AnimationHelper.transitionInDown(555),
  1357. onAction: (index) => {
  1358. switch (index) {
  1359. case 0:
  1360. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1361. break;
  1362. case 1:
  1363. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1364. break;
  1365. case 2:
  1366. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1367. // 1. Sort by type first
  1368. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1369. if (typeOrder !== 0) {
  1370. return typeOrder;
  1371. }
  1372. // 2. Then sort by artist count (numeric comparison)
  1373. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1374. if(this.modeType === 2){
  1375. sortMap = this.artistMap
  1376. }else{
  1377. sortMap = this.albumMap
  1378. }
  1379. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1380. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1381. return aArtistCount - bArtistCount;
  1382. });
  1383. break;
  1384. case 3:
  1385. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1386. // 1. Sort by type first
  1387. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1388. if (typeOrder !== 0) {
  1389. return typeOrder;
  1390. }
  1391. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1392. if(this.modeType === 2){
  1393. sortMap = this.artistMap
  1394. }else{
  1395. sortMap = this.albumMap
  1396. }
  1397. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1398. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1399. return bArtistCount - aArtistCount;
  1400. });
  1401. break;
  1402. }
  1403. this.updateListData(this.videoLocalList)
  1404. }
  1405. })
  1406. return
  1407. }
  1408. //动作面板
  1409. DialogHelper.showBottomSheetDialog({
  1410. title: "请选择排序模式",
  1411. maskColor: Color.Transparent,
  1412. height: '75%',
  1413. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1414. sheets: [
  1415. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1416. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1417. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1418. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1419. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1420. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1421. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1422. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1423. ],
  1424. backgroundColor: $r('app.color.bg_card'),
  1425. transition: AnimationHelper.transitionInDown(555),
  1426. onAction: (index) => {
  1427. this.doSortType(index)
  1428. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1429. this.updateListData(this.videoLocalList, true)
  1430. }
  1431. })
  1432. }
  1433. doSortType(index: number) {
  1434. switch (index) {
  1435. case 0:
  1436. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1437. // 类型排序优先级
  1438. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1439. if (typeOrder !== 0) {
  1440. return typeOrder;
  1441. }
  1442. // 处理艺术家可能为undefined的字符串比较
  1443. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1444. const artistB = b.artist?.trim() || '';
  1445. return artistA.localeCompare(artistB);
  1446. });
  1447. break;
  1448. case 1:
  1449. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1450. // 类型排序优先级
  1451. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1452. if (typeOrder !== 0) {
  1453. return typeOrder;
  1454. }
  1455. // 处理艺术家可能为undefined的字符串比较
  1456. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1457. const artistB = b.artist?.trim() || '';
  1458. return artistB.localeCompare(artistA);
  1459. });
  1460. break;
  1461. case 2:
  1462. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1463. // 类型排序优先级
  1464. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1465. if (typeOrder !== 0) {
  1466. return typeOrder;
  1467. }
  1468. // 处理专辑可能为undefined的字符串比较
  1469. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1470. const albumB = b.album?.trim() || '';
  1471. return albumA.localeCompare(albumB);
  1472. });
  1473. break;
  1474. case 3:
  1475. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1476. // 类型排序优先级
  1477. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1478. if (typeOrder !== 0) {
  1479. return typeOrder;
  1480. }
  1481. // 处理专辑可能为undefined的字符串比较
  1482. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1483. const albumB = b.album?.trim() || '';
  1484. return albumB.localeCompare(albumA);
  1485. });
  1486. break;
  1487. case 4:
  1488. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1489. break;
  1490. case 5:
  1491. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1492. break;
  1493. case 6:
  1494. this.videoLocalList.sort((a, b) => {
  1495. // First, sort by type
  1496. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1497. if (typeOrder !== 0) {
  1498. return typeOrder;
  1499. }
  1500. // If types are the same, sort by cTime in ascending order
  1501. return a.cTime.localeCompare(b.cTime);
  1502. });
  1503. break;
  1504. case 7:
  1505. this.videoLocalList.sort((a, b) => {
  1506. // First, sort by type
  1507. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1508. if (typeOrder !== 0) {
  1509. return typeOrder;
  1510. }
  1511. // If types are the same, sort by cTime in descending order
  1512. return b.cTime.localeCompare(a.cTime);
  1513. });
  1514. break;
  1515. }
  1516. }
  1517. showSheelDialog() {
  1518. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1519. // this.showTips()
  1520. // return
  1521. // }
  1522. this.showAddDialog()
  1523. }
  1524. showAddDialog() {
  1525. if (this.modeType === 2 || this.modeType === 3) {
  1526. return
  1527. }
  1528. DialogHelper.showActionSheetDialog({
  1529. title: "请选择添加方式(建议歌词文件一起导入)",
  1530. sheets: [
  1531. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  1532. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1533. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1534. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1535. ],
  1536. maskColor: Color.Transparent,
  1537. backgroundColor: $r('app.color.bg_card'),
  1538. transition: AnimationHelper.transitionInDown(555),
  1539. onAction: (index) => {
  1540. switch (index) {
  1541. case 0:
  1542. if (this.modeType === 0) {
  1543. this.showMkDialog()
  1544. } else {
  1545. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  1546. }
  1547. break;
  1548. case 1:
  1549. this.callFilePickerSelectFile()
  1550. break;
  1551. case 2:
  1552. this.showTips()
  1553. break;
  1554. case 3:
  1555. this.goSelectMusic()
  1556. break;
  1557. }
  1558. }
  1559. })
  1560. }
  1561. //拉起音频
  1562. goSelectMusic() {
  1563. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1564. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1565. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1566. ) {
  1567. ToastUtil.showToast('暂时不支持该设备')
  1568. return
  1569. }
  1570. try {
  1571. let documentSelectOptions = new picker.DocumentSelectOptions();
  1572. documentSelectOptions.authMode = true
  1573. documentSelectOptions.multiAuthMode = true
  1574. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1575. let documentPicker = new picker.DocumentViewPicker(this.context);
  1576. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1577. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1578. this.saveVideoDatas(documentSelectResult)
  1579. }
  1580. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1581. JSON.stringify(documentSelectResult));
  1582. }).catch((err: BusinessError) => {
  1583. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1584. });
  1585. } catch (error) {
  1586. let err: BusinessError = error as BusinessError;
  1587. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1588. }
  1589. }
  1590. async showTips() {
  1591. DialogHelper.showTipsDialog({
  1592. title: '使用提示:自动导入教程',
  1593. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1594. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1595. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1596. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1597. onAction: (action) => {
  1598. if (action == DialogAction.TWO) {
  1599. PreferencesUtil.putSync('isFirstMusic', false)
  1600. router.pushUrl({
  1601. url: 'pages/ScanFilePage'
  1602. });
  1603. }
  1604. }
  1605. })
  1606. }
  1607. showMkDialog() {
  1608. DialogHelper.showTextInputDialog({
  1609. title: '新建歌单',
  1610. maskColor: Color.Transparent,
  1611. text: '',
  1612. transition: AnimationHelper.transitionInDown(666),
  1613. onChange: (text) => {
  1614. console.error("onChange: " + text);
  1615. },
  1616. onAction: (action, dialogId, content) => {
  1617. // ToastUtil.showToast('content = ' +content)
  1618. if (action == DialogAction.TWO) {
  1619. const newName = content
  1620. const newPath = this.currentPath + '/' + newName
  1621. FileUtil.mkdir(newPath, true).then(() => {
  1622. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1623. this.getSortedFiles(this.currentPath)
  1624. }).catch((error: BusinessError) => {
  1625. console.error(error.message);
  1626. });
  1627. }
  1628. }
  1629. })
  1630. }
  1631. @State progress: number = 0;
  1632. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1633. if (ArrayUtil.isEmpty(uris)) {
  1634. return;
  1635. }
  1636. let newUris: string[] = [];
  1637. this.progress = 0
  1638. DialogHelper.showLoadingProgress({
  1639. progress: this.progress,
  1640. backCancel: false,
  1641. autoCancel: false,
  1642. loadColor: this.themeColor,
  1643. fontColor: this.themeColor
  1644. });
  1645. // 计算所有文件的总大小
  1646. let totalSize = 0;
  1647. for (let uri of uris) {
  1648. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1649. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1650. await fileIo.close(sourceFile.fd);
  1651. }
  1652. let totalRead = 0;
  1653. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1654. Logger.info(TAG, 'destPath uri: ' + destPath);
  1655. for (let i = 0; i < uris.length; i++) {
  1656. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1657. Logger.info(TAG, 'filePath uri: ' + filePath);
  1658. newUris.push(filePath);
  1659. try {
  1660. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1661. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1662. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1663. const buffer = new ArrayBuffer(buffSize);
  1664. let len = await fileIo.read(sourceFile.fd, buffer);
  1665. while (len > 0) {
  1666. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1667. totalRead += len;
  1668. // 计算总进度
  1669. this.progress = Math.floor((totalRead / totalSize) * 100);
  1670. DialogHelper.updateLoading('正在导入', this.progress);
  1671. len = await fileIo.read(sourceFile.fd, buffer);
  1672. }
  1673. await fileIo.close(sourceFile.fd);
  1674. await fileIo.close(destFile.fd);
  1675. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1676. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1677. let mediaItem: VideoItem =
  1678. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1679. this.table.insert(mediaItem, (id: number) => {
  1680. // 删除目标路径缓存
  1681. this.cache.delete(this.currentPath);
  1682. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1683. });
  1684. }
  1685. }
  1686. } catch (error) {
  1687. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1688. }
  1689. }
  1690. DialogHelper.closeLoading()
  1691. this.isZero = false
  1692. // setTimeout(() => {
  1693. // // 删除目标路径缓存
  1694. // this.cache.delete(this.currentPath);
  1695. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1696. // }, 500);
  1697. Logger.info(TAG, 'scan select video result:' + newUris)
  1698. }
  1699. //拉起音频
  1700. // goSelectMusic(){
  1701. //
  1702. // try {
  1703. // let audioSelectOptions = new picker.AudioSelectOptions();
  1704. // let audioPicker = new picker.AudioViewPicker(this.context);
  1705. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1706. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1707. // this.saveVideoDatas(audioSelectResult)
  1708. // }
  1709. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1710. // }).catch((err: BusinessError) => {
  1711. //
  1712. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1713. // });
  1714. // } catch (error) {
  1715. // let err: BusinessError = error as BusinessError;
  1716. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1717. // }
  1718. //
  1719. //
  1720. //
  1721. // }
  1722. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1723. if (!item) {
  1724. return undefined;
  1725. }
  1726. try {
  1727. let selectUris: Array<string> = [];
  1728. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1729. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1730. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1731. photoSelectOptions.maxSelectNumber = 1;
  1732. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1733. selectUris = photoSelectResult.photoUris;
  1734. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1735. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1736. console.info('file fd: ' + file.fd);
  1737. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1738. let imagePath = this.context.filesDir + FileUtil.separator + name
  1739. imagePath = fileUri.getUriFromPath(imagePath)
  1740. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1741. fileIo.copyFileSync(file.fd, file2.fd)
  1742. fileIo.closeSync(file);
  1743. fileIo.closeSync(file2);
  1744. if (item.filePath == this.currentSong?.filePath) {
  1745. this.cover = imagePath
  1746. }
  1747. if (item) {
  1748. item.pixelMapPath = imagePath
  1749. }
  1750. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1751. if (success) {
  1752. this.doUpdateData()
  1753. console.log("onecold 更新音乐封面成功,数据库已同步");
  1754. } else {
  1755. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1756. }
  1757. });
  1758. LogUtil.debug("onecold this.cover =" + this.cover)
  1759. return FileUtil.getFilePath(imagePath); // Return the image path here
  1760. } catch (err) {
  1761. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1762. return undefined;
  1763. }
  1764. }
  1765. // 拉起picker选择文件管理器
  1766. async callFilePickerSelectFile(): Promise<void> {
  1767. try {
  1768. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1769. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1770. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1771. } else {
  1772. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1773. }
  1774. let documentPicker = new picker.DocumentViewPicker();
  1775. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1776. Logger.info(TAG,
  1777. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1778. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1779. this.saveVideoDatas(DocumentSelectResult)
  1780. }
  1781. }).catch((err: BusinessError) => {
  1782. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1783. });
  1784. } catch (err) {
  1785. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1786. }
  1787. }
  1788. //重命名的对话框
  1789. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1790. DialogHelper.showTextInputDialog({
  1791. title: '重命名',
  1792. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1793. maskColor: Color.Transparent,
  1794. backgroundColor: Color.Grey,
  1795. transition: AnimationHelper.transitionInDown(666),
  1796. onChange: (text) => {
  1797. console.error("onChange: " + text);
  1798. },
  1799. onAction: (action, dialogId, content) => {
  1800. // ToastUtil.showToast('content = ' +content)
  1801. if (action == DialogAction.TWO) {
  1802. const newName = content
  1803. const newPath = this.currentPath + '/' + newName
  1804. console.log("onecold item = " + item.type);
  1805. this.doReName(index, newName, filePath, newPath, item)
  1806. }
  1807. }
  1808. })
  1809. }
  1810. //剪切 移动到另个文件夹的对话框
  1811. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1812. Logger.info('onecold showCutDialog')
  1813. let mList: Array<string> = []
  1814. let rPath = this.rootPath
  1815. if (isCurrent) {
  1816. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1817. rPath = this.currentPath
  1818. } else {
  1819. mList = Utility.getNameList(this.dirList);
  1820. rPath = this.rootPath
  1821. }
  1822. let dataBean = new BubbleBean()
  1823. dataBean.data = mList
  1824. dataBean.color = this.themeColor
  1825. dataBean.onItemClick = (i) => {
  1826. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1827. Logger.info('newPath = ' + newPath)
  1828. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1829. ToastUtil.showToast('移动成功')
  1830. this.table.deleteData(item, () => {
  1831. });
  1832. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1833. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1834. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1835. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1836. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1837. this.table.insert(newItem, (id: number) => {
  1838. //加入数据库
  1839. });
  1840. }
  1841. this.cache.delete(this.currentPath); // 删除原路径缓存
  1842. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1843. this.getSortedFiles(this.currentPath, true)
  1844. }).catch((error: BusinessError) => {
  1845. console.error(error.message);
  1846. });
  1847. XPopup.dismissTop()
  1848. }
  1849. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1850. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1851. popupPosition = PopupPosition.TOP
  1852. }
  1853. if (index <= 3) {
  1854. popupPosition = PopupPosition.BOTTOM
  1855. }
  1856. let pup: XPopup
  1857. if (this.isDarkMode) {
  1858. pup = XPopup.Builder()
  1859. .setPopupPosition(popupPosition)
  1860. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1861. .setBackgroundColor(Color.Black)
  1862. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1863. .show()
  1864. } else {
  1865. pup = XPopup.Builder()
  1866. .setPopupPosition(popupPosition)
  1867. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1868. .setBackgroundColor(Color.White)
  1869. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1870. .show()
  1871. }
  1872. }
  1873. //复制 到另个文件夹的对话框
  1874. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1875. Logger.info('onecoldv showCopyDialog')
  1876. let mList: Array<string> = []
  1877. let rPath = this.rootPath
  1878. if (isCurrent) {
  1879. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1880. rPath = this.currentPath
  1881. } else {
  1882. mList = Utility.getNameList(this.dirList);
  1883. rPath = this.rootPath
  1884. }
  1885. let dataBean = new BubbleBean()
  1886. dataBean.data = mList
  1887. dataBean.isCopy = true
  1888. dataBean.color = this.themeColor
  1889. dataBean.onItemClick = (i) => {
  1890. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1891. Logger.info('newPath = ' + newPath)
  1892. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1893. ToastUtil.showToast('复制成功')
  1894. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1895. this.getSortedFiles(this.currentPath)
  1896. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1897. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1898. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1899. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1900. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1901. this.table.insert(newItem, (id: number) => {
  1902. //加入数据库
  1903. });
  1904. }
  1905. }).catch((error: BusinessError) => {
  1906. console.error(error.message);
  1907. });
  1908. XPopup.dismissTop()
  1909. }
  1910. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1911. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1912. popupPosition = PopupPosition.TOP
  1913. }
  1914. if (index <= 3) {
  1915. popupPosition = PopupPosition.BOTTOM
  1916. }
  1917. let pup: XPopup
  1918. if (this.isDarkMode) {
  1919. pup = XPopup.Builder()
  1920. .setPopupPosition(popupPosition)
  1921. .atView(id)
  1922. .setMaxHeight('60%')
  1923. .setBackgroundColor(Color.Black)
  1924. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1925. .show();
  1926. } else {
  1927. pup = XPopup.Builder()
  1928. .setPopupPosition(popupPosition)
  1929. .atView(id)
  1930. .setMaxHeight('60%')
  1931. .setBackgroundColor(Color.White)
  1932. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1933. .show();
  1934. }
  1935. }
  1936. //重命名索引index的视频
  1937. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1938. FileUtil.rename(oldPath, newPath).then(async () => {
  1939. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1940. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1941. //如果是文件夹先删除源数据,再添加新数据
  1942. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1943. if (success) {
  1944. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1945. } else {
  1946. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1947. }
  1948. });
  1949. this.scanDirectory(newPath)
  1950. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1951. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1952. if (success) {
  1953. console.log(" onecold 重命名成功,数据库已同步");
  1954. } else {
  1955. console.error(" onecold 重命名数据库失败原因: " + error);
  1956. }
  1957. });
  1958. }
  1959. let mediaItem: VideoItem =
  1960. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1961. this.videoLocalList[index] = mediaItem;
  1962. }
  1963. this.cache.delete(this.currentPath)
  1964. this.getSortedFiles(this.currentPath, true)
  1965. }).catch((error: BusinessError) => {
  1966. console.error(error.message);
  1967. });
  1968. }
  1969. build() {
  1970. Scroll() {
  1971. Column() {
  1972. if (!this.isShowCoverHeader()) {
  1973. Column() {
  1974. Line().width('100%').height('100%')
  1975. }
  1976. .height(this.topRectHeight)
  1977. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1978. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1979. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1980. TitleBar({ model: $titleBarModel })
  1981. .id('pup_positon_music')
  1982. }
  1983. Stack() {
  1984. Column() {
  1985. XComponent({
  1986. id: 'xcomponentId',
  1987. type: 'surface',
  1988. libraryname: 'ijkplayer_napi',
  1989. controller: this.xcomponentController
  1990. })
  1991. .onLoad((event?: object) => {
  1992. if (!!event) {
  1993. this.initDelayPlay(event);
  1994. }
  1995. })
  1996. .onKeyEvent((event?: KeyEvent) => {
  1997. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1998. if (!event || event.type !== KeyType.Down) {
  1999. return;
  2000. }
  2001. //空格键 Space key controls pause/play
  2002. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  2003. console.info('onecold playOrPause 1999')
  2004. this.playOrPause()
  2005. }
  2006. // Right-click to fast forward
  2007. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2008. this.sessionFastForwardCallback(15);
  2009. }
  2010. // Left-click to rewind
  2011. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2012. this.sessionRewindCallback(15);
  2013. }
  2014. })
  2015. .onDestroy(() => {
  2016. })
  2017. .width('100%')// .width(this.videoWidth)
  2018. .aspectRatio(this.videoAspectRatio)
  2019. }
  2020. .aspectRatio(this.videoAspectRatio)
  2021. .justifyContent(FlexAlign.Center)
  2022. .backgroundColor(Color.Transparent)
  2023. .visibility(Visibility.Hidden)
  2024. .height(CommonConstants.FULL_PERCENT)
  2025. .width(CommonConstants.FULL_PERCENT)
  2026. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2027. height:this.isLandscape?'80%': '43%',
  2028. dragBar: true,
  2029. showClose: true,
  2030. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2031. blurStyle:BlurStyle.Thin,
  2032. backgroundColor:Color.Transparent,
  2033. title: { title: 'AB循环' }
  2034. })
  2035. Stack() {
  2036. Row() {
  2037. Blank()
  2038. .layoutWeight(1)
  2039. IndexerView(
  2040. {
  2041. indexArray: DEFAULT_INDEX,
  2042. selectedIndex: this.selectedIndex,
  2043. textSize: 12,
  2044. selectedColor: "#ff419ee5",
  2045. normalColor: "#ffa0a0a0",
  2046. floatSelectedTextColor: "#ffffff",
  2047. floatSelectedViewColor: "#ff419ee5",
  2048. onIndexChanged: (index) => {
  2049. this.listScroller.scrollToIndex(index)
  2050. }
  2051. })
  2052. .width(24)
  2053. .height("50%")
  2054. }.visibility(Visibility.None)
  2055. Column() {
  2056. if (!this.isShowCoverHeader()) {
  2057. this.tabTitle()
  2058. }
  2059. if(this.twoFingerType==4){
  2060. this.getWaterView()
  2061. }else{
  2062. if(this.isGridMusic){
  2063. this.getGridView()
  2064. }else {
  2065. this.getList()
  2066. }
  2067. }
  2068. if (this.modeType ==0||this.modeType==4) {
  2069. Column() {
  2070. emptyView(this.themeColor)
  2071. }
  2072. .position({ top:this.isShowCoverHeader() ? 260 : 180 })
  2073. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2074. .animation({ duration: 500 }),
  2075. TransitionEffect.scale({ x: 0, y: 0 })))
  2076. .justifyContent(FlexAlign.Center)
  2077. .opacity(this.isZero ? 1 : 0)
  2078. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2079. ? Visibility.Visible : Visibility.None)
  2080. .animation({
  2081. duration: 500,
  2082. curve: 'ease-in-out' // 可选动画曲线
  2083. })
  2084. .width('100%')
  2085. }
  2086. }
  2087. .layoutWeight(1)
  2088. .height('100%')
  2089. }
  2090. .layoutWeight(1)
  2091. .height('100%')
  2092. Row() {
  2093. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2094. .width(50)
  2095. .height(50)
  2096. .fontSize(13)
  2097. .margin({ top: 10, bottom: 10, right: 6 })
  2098. .backgroundColor(this.themeColor)
  2099. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2100. .onClick(() => {
  2101. if (this.isAllSelected) {
  2102. // 全不选
  2103. this.selectedFiles = [];
  2104. } else {
  2105. // 全选
  2106. this.selectedFiles = [...this.getCurFileList()];
  2107. }
  2108. this.isAllSelected = !this.isAllSelected;
  2109. })
  2110. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2111. .width(90)
  2112. .height(50)
  2113. .fontSize(13)
  2114. .margin({ top: 10, bottom: 10, right: 6 })
  2115. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2116. .backgroundColor(this.themeColor)
  2117. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2118. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2119. })
  2120. .onClick(() => {
  2121. this.isOneKeyTags = !this.isOneKeyTags
  2122. })
  2123. Button('乱码修复', { type: ButtonType.Capsule, stateEffect: true })
  2124. .width(90)
  2125. .height(50)
  2126. .fontSize(13)
  2127. .margin({ top: 10, bottom: 10, right: 6 })
  2128. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2129. .backgroundColor(this.themeColor)
  2130. .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2131. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2132. })
  2133. .onClick(() => {
  2134. this.isFixMessy = !this.isFixMessy
  2135. })
  2136. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2137. // .width('35%')
  2138. // .height(60)
  2139. // .id('music_cut')
  2140. // .margin({ top: 10, bottom: 10, right: 6 })
  2141. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2142. // .backgroundColor(this.themeColor)
  2143. // .onClick(() => {
  2144. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2145. // })
  2146. //
  2147. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2148. // .width('35%')
  2149. // .height(60)
  2150. // .id('music_cut_current')
  2151. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2152. // .margin({ top: 10, bottom: 10, right: 6 })
  2153. // .backgroundColor(this.themeColor)
  2154. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2155. // .onClick(() => {
  2156. //
  2157. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2158. // })
  2159. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2160. // .width('35%')
  2161. // .height(60)
  2162. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2163. // .margin({ top: 10, bottom: 10, right: 6 })
  2164. // .backgroundColor(this.themeColor)
  2165. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2166. // .onClick(() => {
  2167. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2168. // })
  2169. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2170. .width(50)
  2171. .height(50)
  2172. .fontSize(13)
  2173. .margin({ top: 10, bottom: 10, right: 6 })
  2174. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2175. .backgroundColor(this.themeColor)
  2176. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2177. .onClick(() => {
  2178. this.showWarnIsDelete()
  2179. })
  2180. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2181. .width(50)
  2182. .height(50)
  2183. .fontSize(13)
  2184. .margin({ top: 10, bottom: 10, right: 6 })
  2185. .backgroundColor(this.themeColor)
  2186. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2187. .onClick(() => {
  2188. this.selectedFiles = [];
  2189. this.isAllSelected = false
  2190. this.isMultiSelect = false
  2191. })
  2192. }
  2193. .width('100%')
  2194. .justifyContent(FlexAlign.Center)
  2195. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2196. .opacity(this.isMultiSelect ? 1 : 0)
  2197. .animation({
  2198. duration: 666,
  2199. curve: 'ease-in-out' // 可选动画曲线
  2200. })
  2201. .position(this.isShowCoverHeader() ? { bottom: 78 }
  2202. : { bottom: this.isPhoneLan() ? 130 : 170 }) // 将 Row 固定在底部
  2203. }
  2204. .width('100%')
  2205. .height('100%')
  2206. .alignContent(Alignment.Top)
  2207. Column() {
  2208. this.PlayController()
  2209. }
  2210. .hitTestBehavior(HitTestMode.Transparent)
  2211. .position({ bottom: 0 }) // 将 Row 固定在底部
  2212. .opacity(this.barBottomOpacity)
  2213. }
  2214. .width('100%')
  2215. .height('100%')
  2216. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2217. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2218. .backgroundImagePosition(Alignment.Center)
  2219. .backdropBlur(this.blurValue)
  2220. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2221. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2222. }
  2223. }
  2224. @Builder
  2225. TagsContentCoverBuilder() {
  2226. Scroll() {
  2227. Column() {
  2228. TagsContentCover(
  2229. {
  2230. selectedFiles:this.selectedFiles,
  2231. isOneKeyTags:this.isOneKeyTags,
  2232. onTagsResult:(result: boolean)=>{
  2233. this.isMultiSelect = false
  2234. if(result){//如果嵌入成功,更新数据
  2235. this.doUpdateData()
  2236. }
  2237. }
  2238. }
  2239. )
  2240. }
  2241. }
  2242. .width('100%')
  2243. .height('100%')
  2244. }
  2245. @Builder
  2246. FixMessyViewBuilder() {
  2247. Scroll() {
  2248. Column() {
  2249. FixMessyView(
  2250. {
  2251. selectedFiles:this.selectedFiles,
  2252. isFixMessy:this.isFixMessy,
  2253. onFixResult:(result: boolean)=>{
  2254. this.isMultiSelect = false
  2255. if(result){//如果嵌入成功,更新数据
  2256. this.doUpdateData()
  2257. }
  2258. }
  2259. }
  2260. )
  2261. }
  2262. }
  2263. .width('100%')
  2264. .height('100%')
  2265. }
  2266. asyncCurrentPathData() {
  2267. if (this.modeType == 0) {
  2268. workerInstance.postMessage({
  2269. code: 1,
  2270. data1: this.context,
  2271. data2: this.currentPath,
  2272. data3: this.lockPath,
  2273. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2274. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  2275. });
  2276. }
  2277. }
  2278. // 处理文件选择的函数
  2279. handleFileSelection(item: VideoItem, checked: boolean) {
  2280. if (checked) {
  2281. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2282. this.selectedFiles.push(item);
  2283. }
  2284. } else {
  2285. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2286. if (index > -1) {
  2287. this.selectedFiles.splice(index, 1);
  2288. }
  2289. }
  2290. }
  2291. private deleteComponentId: number = 0
  2292. //多选删除文件
  2293. showWarnIsDelete(){
  2294. this.getUIContext().getPromptAction().openCustomDialog({
  2295. builder: () => {
  2296. this.deleteComptentBuilder()
  2297. },
  2298. isModal:true,
  2299. showInSubWindow:false,
  2300. maskColor: Color.Transparent,
  2301. dialogTransition: // 设置弹窗内容显示的过渡效果
  2302. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  2303. .animation({ duration: 600, curve: Curve.Smooth }),
  2304. maskTransition: // 设置蒙层显示的过渡效果
  2305. TransitionEffect.opacity(0)
  2306. .animation({ duration: 600, curve: Curve.Smooth })
  2307. }).then((dialogId: number) => {
  2308. this.deleteComponentId = dialogId
  2309. })
  2310. .catch((error: BusinessError) => {
  2311. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  2312. })
  2313. }
  2314. @Builder
  2315. deleteComptentBuilder(){
  2316. DeleteComptent({
  2317. selectedFiles:this.selectedFiles,
  2318. onCancel:()=>{
  2319. this.isMultiSelect = false
  2320. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2321. },
  2322. onDeleteResult:(result: boolean)=>{
  2323. this.isMultiSelect = false
  2324. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2325. if(result){//如果删除成功,更新数据
  2326. this.selectedFiles = [];
  2327. this.isAllSelected = false
  2328. this.cache.delete(this.currentPath);
  2329. this.getSortedFiles(this.currentPath, true);
  2330. }
  2331. }
  2332. })
  2333. }
  2334. //多选移动文件
  2335. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2336. Logger.info('onecold showCutDialogForMultipleFiles')
  2337. let mList: Array<string> = []
  2338. let rPath = this.rootPath
  2339. if (isCurrent) {
  2340. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2341. rPath = this.currentPath
  2342. } else {
  2343. mList = Utility.getNameList(this.dirList);
  2344. rPath = this.rootPath
  2345. }
  2346. let dataBean = new BubbleBean();
  2347. dataBean.data = mList;
  2348. dataBean.color = this.themeColor
  2349. dataBean.onItemClick = (i) => {
  2350. const newDirPath = rPath + '/' + mList[i];
  2351. // Logger.info('newDirPath = ' + newDirPath)
  2352. this.selectedFiles.forEach((item) => {
  2353. const newPath = newDirPath + '/' + item.fileName;
  2354. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2355. ToastUtil.showToast('移动成功');
  2356. this.table.deleteData(item, () => {
  2357. this.cache.delete(this.currentPath); // 删除原路径缓存
  2358. this.cache.delete(newDirPath); // 删除目标路径缓存
  2359. this.getSortedFiles(this.currentPath, true);
  2360. });
  2361. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2362. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2363. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2364. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2365. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2366. this.table.insert(newItem, (id: number) => {
  2367. //加入数据库
  2368. });
  2369. }
  2370. }).catch((error: Error) => {
  2371. console.error(error.message);
  2372. });
  2373. });
  2374. this.isMultiSelect = false
  2375. this.selectedFiles = [];
  2376. this.isAllSelected = false
  2377. XPopup.dismissTop();
  2378. };
  2379. let pup: XPopup
  2380. if (this.isDarkMode) {
  2381. pup = XPopup.Builder()
  2382. .setPopupPosition(PopupPosition.TOP)
  2383. .atView(viewId)
  2384. .setBackgroundColor(Color.Black)
  2385. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2386. .show();
  2387. } else {
  2388. pup = XPopup.Builder()
  2389. .setPopupPosition(PopupPosition.TOP)
  2390. .atView(viewId)
  2391. .setBackgroundColor(Color.White)
  2392. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2393. .show();
  2394. }
  2395. }
  2396. /**
  2397. * 加载所有歌单
  2398. */
  2399. async loadAllPlaylists() {
  2400. try {
  2401. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  2402. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  2403. } catch (error) {
  2404. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  2405. }
  2406. }
  2407. /**
  2408. * 显示添加到歌单对话框
  2409. */
  2410. async showAddToPlaylistDialog(item: VideoItem) {
  2411. // 加载最新的歌单列表
  2412. await this.loadAllPlaylists()
  2413. showAddToPlaylistDialog(
  2414. item,
  2415. this.allPlaylists,
  2416. async (playlistId: string) => {
  2417. // 添加歌曲到歌单
  2418. const success = await this.playlistTable?.addSongToPlaylist(playlistId, item.filePath)
  2419. if (success) {
  2420. ToastUtil.showToast('已添加到歌单')
  2421. // 重新加载歌单列表
  2422. await this.loadAllPlaylists()
  2423. } else {
  2424. ToastUtil.showToast('歌曲已在该歌单中')
  2425. }
  2426. },
  2427. () => {
  2428. LogUtil.info('取消添加到歌单')
  2429. },
  2430. () => {
  2431. // 创建新歌单
  2432. showCreatePlaylistDialog(
  2433. async (name: string, description: string, coverPath?: string) => {
  2434. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  2435. if (success) {
  2436. ToastUtil.showToast('歌单创建成功')
  2437. // 重新加载歌单列表并打开添加对话框
  2438. await this.loadAllPlaylists()
  2439. await this.showAddToPlaylistDialog(item)
  2440. } else {
  2441. ToastUtil.showToast('歌单创建失败')
  2442. }
  2443. },
  2444. () => {
  2445. // 取消创建歌单
  2446. }
  2447. )
  2448. }
  2449. )
  2450. }
  2451. doFav(item: VideoItem) {
  2452. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2453. let isFav = 0
  2454. if (Utility.getIsFav(this.favList, item)) {
  2455. isFav = 0
  2456. } else {
  2457. isFav = 1
  2458. }
  2459. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2460. if (result) {
  2461. if (isFav === 1) {
  2462. ToastUtil.showToast('收藏成功');
  2463. } else {
  2464. ToastUtil.showToast('取消收藏成功');
  2465. }
  2466. this.deleteCache(this.currentPath)
  2467. this.getFavList(false)
  2468. if (this.modeType === 0 && !this.isFavMusic) {
  2469. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2470. this.getSortedFiles(this.currentPath)
  2471. }
  2472. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2473. workerInstance.postMessage({ code: 3, data: this.context });
  2474. workerInstance.postMessage({ code: 4, data: this.context });
  2475. }
  2476. })
  2477. }
  2478. //多选复制文件
  2479. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2480. console.log('onecold showCopyDialogForMultipleFiles');
  2481. let mList: Array<string> = []
  2482. let rPath = this.rootPath
  2483. if (isCurrent) {
  2484. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2485. rPath = this.currentPath
  2486. } else {
  2487. mList = Utility.getNameList(this.dirList);
  2488. rPath = this.rootPath
  2489. }
  2490. let dataBean = new BubbleBean();
  2491. dataBean.data = mList;
  2492. dataBean.isCopy = true
  2493. dataBean.color = this.themeColor
  2494. dataBean.onItemClick = (i) => {
  2495. const newDirPath = rPath + '/' + mList[i];
  2496. // Logger.info('newDirPath = ' + newDirPath)
  2497. this.selectedFiles.forEach((item) => {
  2498. const newPath = newDirPath + '/' + item.fileName;
  2499. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2500. ToastUtil.showToast('复制成功');
  2501. this.cache.delete(newDirPath); // 删除目标路径缓存
  2502. this.getSortedFiles(this.currentPath);
  2503. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2504. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2505. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2506. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2507. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2508. this.table.insert(newItem, (id: number) => {
  2509. //加入数据库
  2510. });
  2511. }
  2512. }).catch((error: Error) => {
  2513. console.error(error.message);
  2514. });
  2515. });
  2516. this.isMultiSelect = false
  2517. this.selectedFiles = [];
  2518. this.isAllSelected = false
  2519. XPopup.dismissTop();
  2520. };
  2521. let pup: XPopup
  2522. if (this.isDarkMode) {
  2523. pup = XPopup.Builder()
  2524. .setPopupPosition(PopupPosition.TOP)
  2525. .atView(viewId)
  2526. .setBackgroundColor(Color.Black)
  2527. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2528. .show();
  2529. } else {
  2530. pup = XPopup.Builder()
  2531. .setPopupPosition(PopupPosition.TOP)
  2532. .atView(viewId)
  2533. .setBackgroundColor(Color.White)
  2534. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2535. .show();
  2536. }
  2537. }
  2538. @Builder
  2539. private DirItem(item: VideoItem, index?: number) {
  2540. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2541. Row() {
  2542. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2543. $r('app.media.music_group'))
  2544. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2545. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2546. .fillColor(this.themeColor)// .fontSize(33)
  2547. .alt($r('app.media.music_group'))
  2548. .borderRadius('100%')
  2549. .clip(true)
  2550. .margin({ left: 20, top: 8, bottom: 8 })
  2551. Column() {
  2552. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2553. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2554. .maxLines(1)// .width('88%')
  2555. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2556. .animation({
  2557. duration: 555,
  2558. curve: 'ease-in-out',
  2559. })
  2560. .transition({
  2561. type: TransitionType.Insert,
  2562. opacity: 0,
  2563. translate: { x: 160 }
  2564. })
  2565. .margin({ left: 10, right: 20 })
  2566. .fontColor($r('app.color.text_color'))
  2567. Row() {
  2568. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2569. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2570. .padding({ top: 8 })
  2571. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2572. .fontColor($r('app.color.text_color'))
  2573. .margin({ left: 10 })
  2574. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2575. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2576. .padding({ top: 8 })
  2577. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2578. .fontColor($r('app.color.text_color'))
  2579. .margin({ left: 10 })
  2580. Blank()
  2581. }
  2582. }
  2583. .height('100%')
  2584. .layoutWeight(1)
  2585. .justifyContent(FlexAlign.Center)
  2586. .alignItems(HorizontalAlign.Start)
  2587. Blank()
  2588. Image($r('app.media.arrow_right'))
  2589. .height(25)
  2590. .margin({ right: 10 })
  2591. .alignSelf(ItemAlign.Center)
  2592. .id(item.filePath)
  2593. }
  2594. }
  2595. .backgroundColor(Color.Transparent)
  2596. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2597. .width('100%')
  2598. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2599. .opacity(this.opacityItem) // 绑定透明度
  2600. }
  2601. isShowDir(dirName: string) {
  2602. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2603. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2604. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2605. if (dirName === undefined) {
  2606. return true
  2607. }
  2608. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2609. return this.isShowSimi
  2610. }
  2611. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2612. return this.isShowFAV
  2613. }
  2614. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2615. return this.isShowHistory
  2616. }
  2617. return true
  2618. }
  2619. @State opacityItem: number = 1; // 控制透明度的状态变量
  2620. @Builder
  2621. private MusicItem(item: VideoItem, index?: number) {
  2622. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2623. Row() {
  2624. Stack() {
  2625. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2626. .fillColor(this.themeColor)
  2627. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2628. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2629. .alt($r('app.media.music_red'))
  2630. .borderRadius('100%')
  2631. .clip(true)
  2632. .draggable(false)
  2633. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2634. .autoResize(true) // 重采样,可减少内存占用
  2635. .opacity(this.opacityItem)// 绑定透明度
  2636. .margin({ left: 20 })
  2637. .gesture(LongPressGesture()
  2638. .onAction(async () => {
  2639. //如果是专辑和艺术家的首页,不能长按
  2640. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2641. return
  2642. //如果是我的收藏 最近播放等也不能长按
  2643. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2644. item.name === LocalMusic.STR_HISTORY_MUSIC
  2645. )
  2646. return
  2647. this.longItemFilePath = item.filePath
  2648. this.tempLyricContent = await this.getLyricContent(item)
  2649. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2650. })
  2651. .onActionEnd((event: GestureEvent) => {
  2652. }))
  2653. .onClick(()=>{
  2654. this.doPlay(item,index)
  2655. this.isShowPlay = true
  2656. })
  2657. }
  2658. Column() {
  2659. Column() {
  2660. Text(this.isShowFileName?item.fileName :item.name)
  2661. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2662. .maxLines(1)
  2663. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2664. .animation({
  2665. duration: 555,
  2666. curve: 'Linear',
  2667. })
  2668. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2669. $r('app.color.text_color'))
  2670. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2671. .padding({right:25})
  2672. .bindPopup(this.longItemFilePath === item.filePath, {
  2673. builder: this.MenuBuilder(item,index,item.filePath),
  2674. placement: Placement.Top,
  2675. // autoCancel: true,
  2676. mask: {color:'#33000000'},
  2677. // popupColor: Color.Yellow,
  2678. enableArrow: false,//是否显示箭头
  2679. showInSubWindow: false,
  2680. onStateChange: (e) => {
  2681. if (!e.isVisible) {
  2682. this.longItemFilePath = ''
  2683. this.tempLyricContent = ''
  2684. }
  2685. }
  2686. })
  2687. .gesture(LongPressGesture()
  2688. .onAction(async () => {
  2689. //如果是专辑和艺术家的首页,不能长按
  2690. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2691. return
  2692. //如果是我的收藏 最近播放等也不能长按
  2693. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2694. item.name === LocalMusic.STR_HISTORY_MUSIC
  2695. )
  2696. return
  2697. this.longItemFilePath = item.filePath
  2698. this.tempLyricContent = await this.getLyricContent(item)
  2699. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2700. })
  2701. .onActionEnd((event: GestureEvent) => {
  2702. })
  2703. )
  2704. Row() {
  2705. Column(){
  2706. Text(item.md5Str?.includes('Lossless')?
  2707. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2708. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2709. .padding({ top: 3,right:6,left:6,bottom:3 })
  2710. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2711. $r('app.color.text_color'))
  2712. .fontWeight(500)
  2713. .borderRadius(12)
  2714. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2715. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2716. .backgroundColor('#FFC107')
  2717. }
  2718. .padding({ top: 8 })
  2719. Text(StrUtil.isEmpty(item.artist) ? item.duration
  2720. :this.twoFingerType==2? item.artist +' ' + item.duration
  2721. : item.artist + ' ' + item?.duration)
  2722. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2723. .padding({ top: 8 ,right:25})
  2724. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  2725. .maxLines(1)
  2726. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2727. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2728. Color.Gray)
  2729. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2730. Blank()
  2731. Text(this.isShowFileName?item.duration:item.size)
  2732. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2733. .padding({ top: 8 })
  2734. .maxLines(1)
  2735. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  2736. ? Visibility.Visible : Visibility.None)
  2737. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2738. Color.Gray)
  2739. .margin({ left: 10 })
  2740. }
  2741. .gesture(LongPressGesture()
  2742. .onAction(async () => {
  2743. //如果是专辑和艺术家的首页,不能长按
  2744. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2745. return
  2746. //如果是我的收藏 最近播放等也不能长按
  2747. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2748. item.name === LocalMusic.STR_HISTORY_MUSIC
  2749. )
  2750. return
  2751. this.longItemFilePath = item.filePath
  2752. this.tempLyricContent = await this.getLyricContent(item)
  2753. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2754. })
  2755. .onActionEnd((event: GestureEvent) => {
  2756. })
  2757. )
  2758. }
  2759. .height('100%')
  2760. .width('100%')
  2761. .margin({ right: 10 })
  2762. .justifyContent(FlexAlign.Center)
  2763. .alignItems(HorizontalAlign.Start)
  2764. }
  2765. .height('100%')
  2766. .margin({ left: 5 })
  2767. .layoutWeight(1)
  2768. Column() {
  2769. Checkbox({ name: 'checkbox' + index })
  2770. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2771. .selectedColor(this.themeColor)
  2772. .shape(CheckBoxShape.CIRCLE)
  2773. .opacity(this.isMultiSelect ? 1 : 0)
  2774. .animation({
  2775. duration: 666,
  2776. curve: 'Smooth' // 可选动画曲线
  2777. })
  2778. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2779. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2780. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  2781. .width(22)
  2782. .height(22)
  2783. ImageAnimator()
  2784. .images(this.imagesF)// 动画数组
  2785. .duration(1000)// 持续
  2786. .state(this.animationState)// 动画状态
  2787. .fillMode(FillMode.Forwards)
  2788. .width(18)
  2789. .margin({ right: 20, top: 8, bottom: 8 })
  2790. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2791. Visibility.None)
  2792. .height(18)
  2793. .iterations(-1) // 播放次数
  2794. }
  2795. }
  2796. }
  2797. .backgroundColor(Color.Transparent)
  2798. .width('100%')
  2799. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2800. }
  2801. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2802. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  2803. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  2804. direction: Direction.Ltr,
  2805. buttonPadding:{top:12,bottom:12},
  2806. backgroundColor: Color.Transparent,
  2807. fontSize:14,
  2808. selectedFontSize:15,
  2809. selectedFontColor:Color.White,
  2810. selectedBackgroundColor: this.themeColor,
  2811. localizedTextPadding: {
  2812. end: LengthMetrics.vp(20),
  2813. start: LengthMetrics.vp(20)
  2814. }
  2815. })
  2816. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  2817. //当胶囊按钮的选择发生变化时调用此函数
  2818. capsuleSelectedIndexesChanged() {
  2819. this.modeType = this.tabSelectedIndexes[0]
  2820. }
  2821. @Builder
  2822. tabTitle() {
  2823. Column({ space: 2 }) {
  2824. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  2825. Line()
  2826. .width('100%')
  2827. .height(1)
  2828. .backgroundColor($r('app.color.index_background'))
  2829. .opacity(this.barOpacity)
  2830. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2831. }
  2832. .width('100%')
  2833. .height(this.topBarHeight)
  2834. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2835. }
  2836. // @Builder
  2837. // tabTitle() {
  2838. // Column() {
  2839. // // 使用 Stack 布局来实现绝对定位效果
  2840. // Stack() {
  2841. // // 背景动画容器
  2842. // Row() {
  2843. // ForEach(this.tabs, (i: string, index) => {
  2844. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2845. // Flex()
  2846. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2847. // .borderRadius(20)
  2848. // .padding(10)
  2849. // .margin(6)
  2850. // .width('100%')
  2851. // .height('100%')
  2852. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2853. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2854. // .opacity(this.modeType === index ? 1 : 0)
  2855. // .animation({
  2856. // duration: 666,
  2857. // playMode: PlayMode.Normal,
  2858. // curve: 'ease-in-out'
  2859. // });
  2860. // }
  2861. // .layoutWeight(1)
  2862. // .margin({
  2863. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2864. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2865. // });
  2866. // });
  2867. // }
  2868. // .width('100%')
  2869. // .height(50);
  2870. //
  2871. // // 导航栏容器
  2872. // Row() {
  2873. // ForEach(this.tabs, (item: string, index) => {
  2874. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2875. // Text(item)
  2876. // .fontSize(16)
  2877. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2878. // .padding(15)
  2879. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2880. // .onClick(() => {
  2881. // this.modeType = index;
  2882. // // this.onModeChange();
  2883. // });
  2884. // }
  2885. // .layoutWeight(1)
  2886. // .stateStyles({
  2887. // pressed: { opacity: 0.6 } // 按压反馈
  2888. // });
  2889. // });
  2890. // }
  2891. // .width('100%')
  2892. // .height(this.topBarHeight)
  2893. // .opacity(this.barOpacity)
  2894. // .backgroundColor(Color.Transparent);
  2895. //
  2896. // }
  2897. // .width('100%')
  2898. // .height(this.topBarHeight)
  2899. // .opacity(this.barOpacity)
  2900. //
  2901. // Line()
  2902. // .width('100%')
  2903. // .height(1)
  2904. // .backgroundColor($r('app.color.index_background'))
  2905. // .opacity(this.barOpacity)
  2906. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2907. // }
  2908. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2909. // }
  2910. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2911. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2912. isShowCoverHeader() {
  2913. if (!this.isShowHeader) {
  2914. return false
  2915. }
  2916. if (this.modeType == 0) {
  2917. if (this.isHistory || this.isFavMusic) {
  2918. return true
  2919. }
  2920. if (this.currentPath != this.rootPath) {
  2921. return true
  2922. }
  2923. }
  2924. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2925. }
  2926. @Builder
  2927. coverHeader() {
  2928. if (this.isShowCoverHeader()) {
  2929. Column() {
  2930. Stack() {
  2931. // 居中标题
  2932. Text('')
  2933. .fontSize(18)
  2934. .fontColor(Color.White)
  2935. .align(Alignment.Center)
  2936. // 左右按钮
  2937. Row() {
  2938. Image($r('app.media.left_back_white'))
  2939. .width(28)
  2940. .height(28)
  2941. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2942. .margin({ left: 12, right: 8 })
  2943. .onClick(() => {
  2944. animateTo({ duration: 555 }, () => {
  2945. this.doSwipBack()
  2946. })
  2947. })
  2948. Blank().flexGrow(1)
  2949. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2950. Image($r('app.media.add'))
  2951. .width(25)
  2952. .height(25)
  2953. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2954. .margin({ left: 8, right: 15 })
  2955. .onClick(() => {
  2956. this.showAddDialog()
  2957. })
  2958. }
  2959. }
  2960. .height(48)
  2961. .width('100%')
  2962. .alignItems(VerticalAlign.Center)
  2963. }
  2964. .height(48)
  2965. .width('100%')
  2966. Row() {
  2967. Column() {
  2968. Image(this.currentTitleCover)
  2969. .height(100)
  2970. .width(100)
  2971. .alt(this.imageLabel)
  2972. .borderRadius(8)
  2973. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2974. }
  2975. .alignItems(HorizontalAlign.Start)
  2976. .margin({ left: 30, top: 3, bottom: 15 })
  2977. Column() {
  2978. Column() {
  2979. Text(this.currentTitleName)
  2980. .fontSize(16)
  2981. .maxLines(1)
  2982. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2983. .fontWeight(FontWeight.Bold)
  2984. .fontColor($r('app.color.text_color'))
  2985. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2986. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2987. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2988. .fontSize(14)
  2989. .padding({ top: 8 })
  2990. .maxLines(1)
  2991. .fontWeight(FontWeight.Bold)
  2992. .fontColor($r('app.color.text_color'))
  2993. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2994. if(this.videoLocalList[0].genre){
  2995. Text(`风格:${this.videoLocalList[0].genre}`)
  2996. .fontSize(14)
  2997. .padding({ top: 8 })
  2998. .maxLines(1)
  2999. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  3000. this.videoLocalList[0].genre.includes(this.UNKONWN)
  3001. ?Visibility.None:Visibility.Visible)
  3002. .fontWeight(FontWeight.Bold)
  3003. .fontColor($r('app.color.text_color'))
  3004. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3005. }
  3006. if(this.videoLocalList[0].year){
  3007. Text(`发行时间:${this.videoLocalList[0].year}`)
  3008. .fontSize(14)
  3009. .padding({ top: 8 })
  3010. .maxLines(1)
  3011. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  3012. this.videoLocalList[0].year.includes(this.UNKONWN)
  3013. ?Visibility.None:Visibility.Visible)
  3014. .fontWeight(FontWeight.Bold)
  3015. .fontColor($r('app.color.text_color'))
  3016. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3017. }
  3018. }
  3019. if(this.modeType != 3){
  3020. Row() {
  3021. Text(`共${this.videoLocalList.length}首歌`)
  3022. .fontSize(13)
  3023. .fontWeight(FontWeight.Bold)
  3024. .padding({ top: 8 })
  3025. .fontColor($r('app.color.text_color'))
  3026. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3027. Blank()
  3028. }
  3029. }
  3030. }
  3031. .height('100%')
  3032. .width('100%')
  3033. .justifyContent(FlexAlign.Center)
  3034. .alignItems(HorizontalAlign.Start)
  3035. }
  3036. .height('100%')
  3037. .layoutWeight(1)
  3038. .margin({ left: 20 })
  3039. }
  3040. this.listViewTitle()
  3041. }
  3042. .backgroundImage(this.getCoverTitleBg())
  3043. .height(250)
  3044. .width('100%')
  3045. .backgroundImageSize({ height: '100%', width: '100%' })
  3046. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  3047. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  3048. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  3049. .justifyContent(FlexAlign.SpaceBetween)
  3050. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  3051. TransitionEffect.scale({ x: 0, y: 0 })))
  3052. } else {
  3053. this.listViewTitle()
  3054. }
  3055. }
  3056. getCoverTitleBg(): ResourceStr | image.PixelMap {
  3057. if (this.isCustomizeBg) {
  3058. return ('rgba(255,255,255,0.2)')
  3059. }
  3060. if (this.isDarkMode) {
  3061. return $r('app.color.user_center_card_background')
  3062. }
  3063. return this.currentTitleCover
  3064. }
  3065. @Builder
  3066. listViewTitle() {
  3067. Column() {
  3068. Row({ space: 8 }) {
  3069. Row({ space: 8 }) {
  3070. Image($r("app.media.hm_playlist"))
  3071. .width(25)
  3072. .margin({ left: 8 })
  3073. .fillColor(this.themeColor)
  3074. Text(this.artistList.length ==100 ? `共找到${this.artistCount}位艺术家`
  3075. :`共找到${this.artistList.length}位艺术家`)
  3076. .fontColor($r('app.color.text_color'))
  3077. .fontSize(14)
  3078. .opacity(this.opacityItem)
  3079. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3080. Text(this.albumList.length ==100 ? `共找到${this.albumCount+''}张专辑`
  3081. :`共找到${this.albumList.length}张专辑`)
  3082. .fontColor($r('app.color.text_color'))
  3083. .opacity(this.opacityItem)
  3084. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3085. .fontSize(14)
  3086. }
  3087. .layoutWeight(1)
  3088. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3089. Row() {
  3090. TextInput({
  3091. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  3092. text: this.searchText
  3093. })
  3094. .height(35)
  3095. .onChange((value: string) => {
  3096. this.onSearchInput(value);
  3097. })
  3098. .layoutWeight(1)
  3099. Text(`取消`)
  3100. .margin({ left: 10, right: 10 })
  3101. .fontColor($r('app.color.text_color'))
  3102. .fontSize(16)
  3103. .onClick(() => {
  3104. this.isSearchMode = false
  3105. this.searchText = ''
  3106. if (this.modeType === 2) {
  3107. this.updateListData(this.artistList)
  3108. } else {
  3109. this.updateListData(this.albumList)
  3110. }
  3111. })
  3112. }
  3113. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3114. .animation({
  3115. duration: 666,
  3116. curve: 'ease-in-out' // 可选动画曲线
  3117. })
  3118. Blank()
  3119. Image($r("app.media.search"))
  3120. .width(25)
  3121. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3122. .animation({
  3123. duration: 666,
  3124. curve: 'ease-in-out' // 可选动画曲线
  3125. })// .opacity(this.opacityItem)
  3126. .fillColor(this.themeColor)
  3127. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3128. .onClick(() => {
  3129. this.isSearchMode = true
  3130. })
  3131. Image($r("app.media.top_rank"))
  3132. .width(25)// .opacity(this.opacityItem)
  3133. .fillColor(this.themeColor)
  3134. .animation({
  3135. duration: 666,
  3136. curve: 'ease-in-out' // 可选动画曲线
  3137. })
  3138. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3139. .onClick(() => {
  3140. this.showRankDialog()
  3141. })
  3142. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3143. .width(25)
  3144. .animation({
  3145. duration: 666,
  3146. curve: 'ease-in-out' // 可选动画曲线
  3147. })
  3148. .fillColor(this.themeColor)
  3149. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3150. .onClick(() => {
  3151. this.isGridMusic = !this.isGridMusic
  3152. })
  3153. }
  3154. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  3155. Visibility.None)
  3156. .width('100%')
  3157. .padding(10)
  3158. .height(50)
  3159. .border({
  3160. width: { bottom: 1 },
  3161. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3162. })
  3163. Row({ space: 8 }) {
  3164. Row({ space: 8 }) {
  3165. Image($r("app.media.hm_play"))
  3166. .width(25)
  3167. .margin({ left: 8 })
  3168. .fillColor(this.themeColor)
  3169. Text(`播放全部`)
  3170. .fontColor($r('app.color.text_color'))
  3171. .fontSize(14)
  3172. .animation({
  3173. duration: 666,
  3174. curve: 'ease-in-out' // 可选动画曲线
  3175. })
  3176. if(Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length>0){
  3177. Text(this.modeType==1&&Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length==100?
  3178. `(${this.mediaKuCount}首)`
  3179. :`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  3180. .fontColor($r('app.color.text_color'))
  3181. .fontSize(14)
  3182. .opacity(this.opacityItem)
  3183. .animation({
  3184. duration: 666,
  3185. curve: 'ease-in-out' // 可选动画曲线
  3186. })
  3187. }
  3188. }
  3189. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3190. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3191. .animation({
  3192. duration: 666,
  3193. curve: 'ease-in-out' // 可选动画曲线
  3194. })
  3195. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  3196. .onTouch((event: TouchEvent) => {
  3197. if (event.type === TouchType.Down) {
  3198. this.isClickedPLayAll = true;
  3199. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  3200. this.isClickedPLayAll = false;
  3201. }
  3202. })
  3203. .onClick(() => {
  3204. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  3205. if (this.modeType === 0) {
  3206. const playList = this.getCurFileList();
  3207. const item = Utility.getPlayItem(playList, this.playType);
  3208. if (item) { // 显式检查undefined
  3209. this.doPlay(item);
  3210. }
  3211. } else {
  3212. const item = Utility.getPlayItem(this.mediaKuList, this.playType);
  3213. if (item) {
  3214. this.doPlay(item);
  3215. }
  3216. }
  3217. })
  3218. Row() {
  3219. TextInput({ placeholder: '输入名称...', text: this.searchText })
  3220. .height(35)
  3221. .onChange((value: string) => {
  3222. this.onSearchInput(value);
  3223. })
  3224. .layoutWeight(1)
  3225. Text(`取消`)
  3226. .margin({ left: 10, right: 10 })
  3227. .fontColor($r('app.color.text_color'))
  3228. .fontSize(16)
  3229. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3230. .onClick(() => {
  3231. this.isSearchMode = false
  3232. this.searchText = ''
  3233. if(this.modeType==0){
  3234. this.updateListData(this.videoLocalList)
  3235. } else if(this.modeType==1){
  3236. this.updateListData(this.mediaKuList)
  3237. } else if(this.modeType==2&&!this.isCanBack){
  3238. this.updateListData(this.artistList)
  3239. } else if(this.modeType==3&&!this.isCanBack){
  3240. this.updateListData(this.albumList)
  3241. }else if(this.modeType==4){
  3242. this.doSongListTask()
  3243. }
  3244. })
  3245. }
  3246. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3247. .animation({
  3248. duration: 666,
  3249. curve: 'ease-in-out' // 可选动画曲线
  3250. })
  3251. Blank()
  3252. Image($r("app.media.search"))
  3253. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  3254. .animation({
  3255. duration: 666,
  3256. curve: 'ease-in-out' // 可选动画曲线
  3257. })// .opacity(this.opacityItem)
  3258. .fillColor(this.themeColor)
  3259. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3260. .onClick(() => {
  3261. this.isSearchMode = true
  3262. })
  3263. Image($r("app.media.refresh"))
  3264. .fillColor(this.themeColor)
  3265. .width(25)
  3266. .visibility(this.modeType ==4||this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3267. .animation({
  3268. duration: 666,
  3269. curve: 'ease-in-out' // 可选动画曲线
  3270. })
  3271. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3272. .onClick(() => {
  3273. if (this.isFavMusic) {
  3274. this.getFavList(true)
  3275. } else {
  3276. if(this.modeType == 0){
  3277. this.asyncCurrentPathData()
  3278. }else if(this.modeType ==1){
  3279. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3280. }
  3281. }
  3282. })
  3283. Image($r("app.media.top_rank"))
  3284. .width(25)
  3285. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  3286. Visibility.Visible)// .opacity(this.opacityItem)
  3287. .animation({
  3288. duration: 666,
  3289. curve: 'ease-in-out' // 可选动画曲线
  3290. })
  3291. .fillColor(this.themeColor)
  3292. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3293. .onClick(() => {
  3294. this.showRankDialog()
  3295. })
  3296. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  3297. .width(24)
  3298. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3299. .animation({
  3300. duration: 666,
  3301. curve: 'ease-in-out' // 可选动画曲线
  3302. })
  3303. .fillColor(this.themeColor)
  3304. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3305. .onClick(() => {
  3306. this.isMultiSelect = !this.isMultiSelect
  3307. })
  3308. SymbolGlyph($r('sys.symbol.trash'))
  3309. .fontColor([this.themeColor])
  3310. .fontSize(25)
  3311. .effectStrategy(1)
  3312. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  3313. .animation({
  3314. duration: 666,
  3315. curve: 'ease-in-out' // 可选动画曲线
  3316. })
  3317. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3318. .onClick(() => {
  3319. this.clearVideoHistory() //清空播放记录
  3320. })
  3321. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3322. .width(24)
  3323. .animation({
  3324. duration: 666,
  3325. curve: 'ease-in-out' // 可选动画曲线
  3326. })
  3327. .fillColor(this.themeColor)
  3328. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3329. .bindPopup($$this.tipPopup, {
  3330. builder: this.popupBuilder,
  3331. placement: Placement.Bottom,
  3332. maskColor: 0x33000000,
  3333. enableArrow: true,
  3334. onStateChange: (e) => {
  3335. if (!e.isVisible) {
  3336. this.tipPopup = false;
  3337. }
  3338. }
  3339. })
  3340. .onClick(() => {
  3341. if(this.twoFingerType==4){
  3342. this.isGridMusic = false
  3343. this.twoFingerType=3
  3344. }else{
  3345. this.isGridMusic = !this.isGridMusic
  3346. }
  3347. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3348. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3349. })
  3350. }
  3351. .width('100%')
  3352. .padding(10)
  3353. .height(50)
  3354. .visibility(this.modeType === 0 || this.modeType === 1||this.modeType === 4
  3355. || this.isCanBack ? Visibility.Visible : Visibility.None)
  3356. .border({
  3357. width: { bottom: 1 },
  3358. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3359. })
  3360. }
  3361. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3362. }
  3363. // 第二步:popup构造器定义弹框内容
  3364. @Builder popupBuilder() {
  3365. Column({ space: 2 }) {
  3366. Text('友情提示:双指缩放可以放大缩小列表')
  3367. .fontSize(12)
  3368. .fontWeight(FontWeight.Regular)
  3369. .fontColor($r('app.color.text_color'))
  3370. }
  3371. .justifyContent(FlexAlign.SpaceAround)
  3372. .width(220)
  3373. .height(55)
  3374. .padding(15)
  3375. }
  3376. //搜索功能的实现
  3377. @State searchText: string = ''; // 用户输入内容
  3378. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3379. @State isSearchMode: boolean = false
  3380. // 实时搜索逻辑(带防抖)
  3381. private onSearchInput(value: string) {
  3382. this.searchText = value.trim();
  3383. let mSearchList: Array<VideoItem> = []
  3384. switch (this.modeType) {
  3385. case 0:
  3386. // mSearchList = this.videoLocalList
  3387. // break;
  3388. case 1:
  3389. mSearchList = this.mediaKuList
  3390. break;
  3391. case 2:
  3392. mSearchList = this.artistList
  3393. break;
  3394. case 3:
  3395. mSearchList = this.albumList
  3396. break;
  3397. }
  3398. // 新增条件判断:空输入时显示所有数据
  3399. if (this.searchText === '') {
  3400. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3401. } else {
  3402. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3403. //支持模糊匹配和艺术家 专辑匹配
  3404. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  3405. return regex.test(item.name.toLowerCase())||
  3406. regex.test(item.fileName?.toLowerCase() ?? "") ||
  3407. regex.test(item.artist?.toLowerCase() ?? "") ||
  3408. regex.test(item.album?.toLowerCase() ?? "")
  3409. });
  3410. }
  3411. this.updateListData(this.filteredList);
  3412. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3413. }
  3414. @State dragItem: number = -1
  3415. @State scaleItem: number = -1
  3416. @State neighborItem: number = -1
  3417. @State neighborScale: number = -1
  3418. @State offsetY: number = 0
  3419. private dragRefOffset: number = 0
  3420. private ITEM_INTV: number = 78
  3421. scaleSelect(item: number): number {
  3422. if (this.scaleItem === item) {
  3423. return 1.05
  3424. } else if (this.neighborItem === item) {
  3425. return this.neighborScale
  3426. } else {
  3427. return 1
  3428. }
  3429. }
  3430. itemMove(index: number, newIndex: number): void {
  3431. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3432. return;
  3433. }
  3434. let tmp = this.videoLocalList.splice(index, 1);
  3435. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3436. this.dataSource.pushArrayData(this.videoLocalList)
  3437. }
  3438. //瀑布流布局 支持双指缩放
  3439. @State columns: number = 2;
  3440. @State waterFlowScale: number = 1;
  3441. @State imageScale: number = 1;
  3442. @State waterFlowOpacity: number = 1;
  3443. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  3444. private columnChanged: boolean = false;
  3445. private oldColumn: number = this.columns;
  3446. private pinchTime: number = 0;
  3447. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  3448. changeColumns(scale: number) {
  3449. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3450. this.columns--;
  3451. this.columnChanged = true;
  3452. } else if (scale < 1 && this.columns < 4) {
  3453. this.columns++;
  3454. this.columnChanged = true;
  3455. }
  3456. }
  3457. @Builder
  3458. getWaterView(){
  3459. Scroll(this.scroller) {
  3460. Column() {
  3461. if(this.isShowCoverHeader()){
  3462. this.coverHeader()
  3463. }else {
  3464. this.listViewTitle()
  3465. }
  3466. WaterFlow({
  3467. scroller:this.waterScroller,
  3468. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  3469. }) {
  3470. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3471. FlowItem() {
  3472. this.MusicWaterCardItem(item,index)
  3473. }
  3474. .width('100%')
  3475. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3476. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3477. {
  3478. preview: MenuPreviewMode.IMAGE,
  3479. previewAnimationOptions: { scale: [0.8, 1.0] },
  3480. })
  3481. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3482. {
  3483. preview: MenuPreviewMode.IMAGE,
  3484. previewAnimationOptions: { scale: [0.8, 1.0] },
  3485. })
  3486. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  3487. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3488. TransitionEffect.scale({ x: 0, y: 0 })))
  3489. .gesture(
  3490. GestureGroup(GestureMode.Exclusive,
  3491. SwipeGesture({ direction: SwipeDirection.Horizontal })
  3492. .onAction((event: GestureEvent) => {
  3493. if (event) {
  3494. // this.sideBarController.openSideBar()
  3495. }
  3496. }),
  3497. TapGesture({ count: 1, fingers: 1 })
  3498. .onAction(async () => {
  3499. })
  3500. )
  3501. )
  3502. }, (item: VideoItem) => item.filePath)
  3503. }
  3504. // .columnsTemplate('repeat(auto-fit, 160)')
  3505. .id('waterflow') // 设置id用于截图
  3506. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  3507. .columnsGap(12) // 列间距
  3508. .rowsGap(16) // 行间距
  3509. .cachedCount(6)
  3510. // .margin(
  3511. // this.isHiCar()?{bottom:this.bottomBarHeight+90}:
  3512. // {bottom:this.isShowCoverHeader()? this.topBarHeight+35:
  3513. // this.isCoverOpacity()?this.topBarHeight+this.bottomBarHeight+78
  3514. // :this.topBarHeight+this.bottomBarHeight+108})
  3515. .margin({
  3516. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  3517. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  3518. })
  3519. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3520. .animation({ duration: 500, curve: Curve.Ease }))
  3521. .scrollBar(BarState.Off)
  3522. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  3523. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  3524. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  3525. .width('100%')
  3526. .height('100%')
  3527. .padding(10)
  3528. .opacity(this.waterFlowOpacity)
  3529. .scale({
  3530. x: this.waterFlowScale,
  3531. y: this.waterFlowScale,
  3532. centerX: 0,
  3533. centerY: 0
  3534. })
  3535. .onAppear(() => {
  3536. this.scroller.scrollEdge(Edge.Top)
  3537. })
  3538. .nestedScroll({
  3539. scrollForward: NestedScrollMode.PARENT_FIRST,
  3540. scrollBackward: NestedScrollMode.SELF_FIRST
  3541. })
  3542. .priorityGesture(
  3543. PinchGesture()
  3544. .onActionStart((event: GestureEvent) => {
  3545. // 双指捏合手势识别成功时截图
  3546. this.pinchTime = event.timestamp;
  3547. this.columnChanged = false;
  3548. this.oldColumn = this.columns;
  3549. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  3550. if (error) {
  3551. console.info('error:' + JSON.stringify(error));
  3552. return;
  3553. }
  3554. this.waterFlowSnapshot = pixmap;
  3555. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  3556. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  3557. if (this.oldColumn ===4) {
  3558. this.twoFingerType =3
  3559. this.isGridMusic = true
  3560. }else if (this.oldColumn ===1) {
  3561. this.twoFingerType =1
  3562. this.isGridMusic = false
  3563. }
  3564. return;
  3565. }
  3566. })
  3567. })
  3568. .onActionUpdate((event: GestureEvent) => {
  3569. // 手势更新:处理缩放逻辑和视觉效果
  3570. // 边界限制:防止超出列数范围时继续缩放
  3571. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  3572. return;
  3573. }
  3574. // 节流处理:避免过于频繁的更新,提升性能
  3575. if (event.timestamp - this.pinchTime < 10000000) {
  3576. return;
  3577. }
  3578. this.pinchTime = event.timestamp;
  3579. this.waterFlowScale = event.scale;
  3580. this.imageScale = event.scale;
  3581. // 根据缩放比例设置WaterFlow透明度
  3582. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  3583. this.waterFlowOpacity *= 3;
  3584. if (!this.columnChanged) {
  3585. this.changeColumns(event.scale);
  3586. }
  3587. // 列数改变后的缩放比例调整:避免出现空白区域
  3588. if (this.columnChanged) {
  3589. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  3590. // 限制缩放范围,确保视觉效果自然
  3591. if (event.scale < 1) {
  3592. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  3593. } else {
  3594. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  3595. }
  3596. }
  3597. })
  3598. .onActionEnd((event: GestureEvent) => {
  3599. // 手势结束:执行归位动画并保存状态
  3600. // 执行归位动画:平滑过渡到正常状态
  3601. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  3602. this.waterFlowScale = 1;
  3603. this.waterFlowOpacity = 1;
  3604. })
  3605. // 持久化保存当前列数:下次启动时恢复
  3606. PreferencesUtil.putSync('lastColumns', this.columns);
  3607. })
  3608. )
  3609. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3610. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3611. .onDrop((event?: DragEvent) => {
  3612. try {
  3613. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3614. if (dragData !== undefined) {
  3615. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3616. if (records.length > 0) {
  3617. for (let i = 0; i < records.length; i++) {
  3618. let types = records[i].getTypes();
  3619. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3620. const fileUriUds =
  3621. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3622. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3623. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3624. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3625. this.targetFile = fileUriUds.oriUri;
  3626. this.saveVideoDatas([this.targetFile])
  3627. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3628. }
  3629. }
  3630. }
  3631. } else {
  3632. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3633. }
  3634. } else {
  3635. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3636. }
  3637. } catch (error) {
  3638. const err = error as BusinessError;
  3639. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3640. }
  3641. })
  3642. }
  3643. }
  3644. .scrollBar(BarState.Off)
  3645. }
  3646. //瀑布流卡片布局
  3647. @Builder
  3648. private MusicWaterCardItem(item: VideoItem, index: number) {
  3649. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3650. Stack() {
  3651. Column() {
  3652. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3653. .backgroundImageSize(ImageSize.Auto)
  3654. .borderRadius({
  3655. topLeft: 12,
  3656. topRight : 12,
  3657. bottomLeft: 0,
  3658. bottomRight: 0
  3659. })
  3660. .draggable(false)// 禁止长按手势拖动
  3661. // .autoResize(true) // 重采样,可减少内存占用
  3662. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3663. .width('100%')
  3664. .height('auto')
  3665. .objectFit(ImageFit.Auto)
  3666. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3667. height: '99%' ,
  3668. dragBar: true,
  3669. onDisappear: () => {
  3670. this.longItemFilePath = '';
  3671. this.tempLyricContent = ''
  3672. },
  3673. showClose: true,
  3674. preferType: SheetType.CENTER ,
  3675. title: { title: '编辑标签' }
  3676. })
  3677. .draggable(false)
  3678. .opacity(this.opacityItem)// 绑定透明度
  3679. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3680. // .animation({ duration: 500, curve: Curve.Ease }))
  3681. .animation({
  3682. duration: 666,
  3683. curve: 'ease-in-out' // 可选动画曲线
  3684. })
  3685. .margin({
  3686. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3687. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3688. })
  3689. Column() {
  3690. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3691. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  3692. .maxLines(1)
  3693. .fontWeight(FontWeight.Bold)
  3694. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3695. .animation({
  3696. duration: 555,
  3697. curve: 'Linear',
  3698. })
  3699. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3700. height: '95%',
  3701. dragBar: true,
  3702. showClose: true,
  3703. onDisappear: () => {
  3704. this.longItemFilePathDetail = '';
  3705. },
  3706. blurStyle:BlurStyle.Thin,
  3707. backgroundColor:Color.Transparent,
  3708. preferType: SheetType.CENTER ,
  3709. title: { title: '详情' }
  3710. })
  3711. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3712. $r('app.color.text_color'))
  3713. Column() {
  3714. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3715. .fontSize(11)
  3716. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3717. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3718. .fontColor($r('app.color.text_color'))
  3719. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3720. .fontSize(11)
  3721. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3722. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3723. .fontColor($r('app.color.text_color'))
  3724. Row(){
  3725. Column(){
  3726. Text(item.md5Str?.includes('Lossless')?
  3727. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3728. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  3729. .padding({ top: 3,right:6,left:6,bottom:3 })
  3730. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3731. $r('app.color.text_color'))
  3732. .fontWeight(500)
  3733. .borderRadius(12)
  3734. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3735. .backgroundColor('#FFC107')
  3736. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  3737. }
  3738. .margin({ top: 2 ,right:6})
  3739. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3740. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3741. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3742. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  3743. .maxLines(1)
  3744. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3745. .margin({ top: 2})
  3746. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3747. || item.type == CommonConstants.TYPE_IS_ALBUM
  3748. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3749. .fontWeight(FontWeight.Medium)
  3750. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3751. $r('app.color.text_color'))
  3752. }
  3753. }
  3754. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3755. }
  3756. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  3757. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  3758. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  3759. .width('100%')
  3760. .justifyContent(FlexAlign.Center)
  3761. .margin({
  3762. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3763. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3764. })
  3765. }
  3766. .width('100%')
  3767. .borderRadius(12)
  3768. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3769. .backgroundImageSize({ height: '100%', width: '100%' })
  3770. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3771. .animation({ curve: Curve.Sharp, duration: 300 })
  3772. Checkbox({ name: 'checkbox' + index })
  3773. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3774. .selectedColor(this.themeColor)
  3775. .shape(CheckBoxShape.CIRCLE)
  3776. .opacity(this.isMultiSelect ? 1 : 0)
  3777. .animation({
  3778. duration: 666,
  3779. curve: 'Smooth' // 可选动画曲线
  3780. })
  3781. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3782. Visibility.None)
  3783. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3784. .margin({ left: 20, top: 8, bottom: 8 })
  3785. .width(38)
  3786. .height(38)
  3787. }
  3788. }
  3789. .backgroundColor(Color.Transparent)
  3790. .width('100%')
  3791. .height('auto')
  3792. .padding({top:2})
  3793. .reuseId('card_item')
  3794. .onClick(() => {
  3795. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3796. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3797. this.handleFileSelection(item, !isChecked);
  3798. } else {
  3799. this.doPlay(item, index)
  3800. }
  3801. })
  3802. }
  3803. // Grid布局的开始
  3804. private dragRefOffSetX: number = 0;
  3805. private dragRefOffSetY: number = 0;
  3806. private FIX_VP_X: number = 180;
  3807. private FIX_VP_Y: number = 84;
  3808. isDraggable(index: number): boolean {
  3809. return index >= 0;
  3810. }
  3811. getRowEnd(item: number) {
  3812. if (item.toString() === '0') {
  3813. return 1;
  3814. } else {
  3815. return 0;
  3816. }
  3817. }
  3818. isInLeft(index: number) {
  3819. return index % 2 == 0;
  3820. }
  3821. down(index: number): void {
  3822. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  3823. return;
  3824. }
  3825. this.offsetY -= this.FIX_VP_Y;
  3826. this.dragRefOffSetY += this.FIX_VP_Y;
  3827. this.itemMove(index, index + 1);
  3828. }
  3829. up(index: number): void {
  3830. if (!this.isDraggable(index - 2)) {
  3831. return;
  3832. }
  3833. this.offsetY += this.FIX_VP_Y;
  3834. this.dragRefOffSetY -= this.FIX_VP_Y;
  3835. this.itemMove(index, index - 1);
  3836. }
  3837. left(index: number): void {
  3838. if (this.isInLeft(index)) {
  3839. return;
  3840. }
  3841. if (!this.isDraggable(index - 1)) {
  3842. return;
  3843. }
  3844. this.offsetX += this.FIX_VP_X;
  3845. this.dragRefOffSetX -= this.FIX_VP_X;
  3846. this.itemMove(index, index - 1)
  3847. }
  3848. right(index: number): void {
  3849. if (!this.isInLeft(index)) {
  3850. return;
  3851. }
  3852. if (!this.isDraggable(index + 1)) {
  3853. return;
  3854. }
  3855. this.offsetX -= this.FIX_VP_X;
  3856. this.dragRefOffSetX += this.FIX_VP_X;
  3857. this.itemMove(index, index + 1)
  3858. }
  3859. private scroller: Scroller = new Scroller();
  3860. private waterScroller: Scroller = new Scroller();
  3861. @State startIndex: number = 0
  3862. @State endIndex: number = 0
  3863. @State scaleValue: number = 1
  3864. @State pinchValue: number = 1
  3865. layoutOptionsForHeader: GridLayoutOptions = {
  3866. regularSize: [1, 1], // 只支持[1, 1]
  3867. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3868. };
  3869. @Builder
  3870. getGridView() {
  3871. Grid(this.scroller, this.layoutOptionsForHeader) {
  3872. GridItem() {
  3873. if (this.isShowCoverHeader()) {
  3874. this.coverHeader()
  3875. } else {
  3876. this.listViewTitle()
  3877. }
  3878. }
  3879. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3880. GridItem() {
  3881. Stack({ alignContent: Alignment.Center }) {
  3882. this.MusicItemGrid(item, index)
  3883. }
  3884. }
  3885. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3886. {
  3887. preview: MenuPreviewMode.IMAGE,
  3888. previewAnimationOptions: { scale: [0.8, 1.0] },
  3889. })
  3890. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3891. {
  3892. preview: MenuPreviewMode.IMAGE,
  3893. previewAnimationOptions: { scale: [0.8, 1.0] },
  3894. })
  3895. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3896. TransitionEffect.scale({ x: 0, y: 0 })))
  3897. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3898. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3899. .zIndex(this.dragItem === index ? 1 : 0)
  3900. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3901. }, (item: VideoItem) => item.filePath)
  3902. }
  3903. .width(this.isShowHeader ? '100%' : '94%')
  3904. .height('100%')
  3905. .editMode(true)
  3906. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3907. .animation({ duration: 500, curve: Curve.Ease }))
  3908. .margin(
  3909. this.isHiCar()?{bottom:this.bottomBarHeight+98}:
  3910. {
  3911. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3912. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3913. })
  3914. .reuseId('grid_item')
  3915. .layoutWeight(1)
  3916. .scrollBar(BarState.Off)
  3917. .supportAnimation(true)
  3918. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3919. .columnsTemplate(
  3920. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3921. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3922. )
  3923. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3924. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3925. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3926. .gesture(PinchGesture({ fingers: 2 })
  3927. .onActionEnd((event: GestureEvent) => {
  3928. this.setGridTwoFingers()
  3929. })
  3930. .onActionUpdate(e => {
  3931. this.scaleValue = this.pinchValue * e.scale
  3932. })
  3933. .onActionStart(e => {
  3934. }))
  3935. .enableScrollInteraction(true)
  3936. .onScrollIndex((start: number, end: number) => {
  3937. this.startIndex = start
  3938. this.endIndex = end
  3939. })
  3940. .onScrollFrameBegin((offset: number) => {
  3941. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3942. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3943. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3944. if (this.isScrollHide) {
  3945. this.setBarHeightHide2(offset)
  3946. } else {
  3947. this.setBarHeightNormal()
  3948. }
  3949. } else {
  3950. this.setBarHeightHide(offset)
  3951. }
  3952. return { offsetRemain: offset };
  3953. })
  3954. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3955. .onDrop((event?: DragEvent) => {
  3956. try {
  3957. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3958. if (dragData !== undefined) {
  3959. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3960. if (records.length > 0) {
  3961. for (let i = 0; i < records.length; i++) {
  3962. let types = records[i].getTypes();
  3963. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3964. const fileUriUds =
  3965. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3966. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3967. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3968. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3969. this.targetFile = fileUriUds.oriUri;
  3970. this.saveVideoDatas([this.targetFile])
  3971. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3972. }
  3973. }
  3974. }
  3975. } else {
  3976. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3977. }
  3978. } else {
  3979. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3980. }
  3981. } catch (error) {
  3982. const err = error as BusinessError;
  3983. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3984. }
  3985. })
  3986. }
  3987. @State targetFile: string = '';
  3988. setGridTwoFingers() {
  3989. this.pinchValue = this.scaleValue;
  3990. Logger.info('this.pinchValue = ' + this.pinchValue);
  3991. if (this.pinchValue >= 1) {
  3992. this.twoFingerType++
  3993. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3994. if(this.twoFingerType >= 4){
  3995. this.twoFingerType = 4//切换成瀑布流
  3996. this.columns = 4
  3997. }
  3998. } else {
  3999. this.twoFingerType--
  4000. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4001. if (this.twoFingerType < 1) {
  4002. this.twoFingerType = 3
  4003. this.isGridMusic = false
  4004. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4005. }
  4006. }
  4007. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4008. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4009. this.pinchValue = 1;
  4010. this.scaleValue = 1;
  4011. }
  4012. @State longItemFilePath: string = ''
  4013. @State tempLyricContent: string = ''
  4014. @Builder
  4015. private MusicItemGrid(item: VideoItem, index: number) {
  4016. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4017. Stack() {
  4018. Column() {
  4019. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  4020. .height(this.getGridHeight())
  4021. .width(this.getGridWight())
  4022. .draggable(false)
  4023. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4024. .autoResize(true) // 重采样,可减少内存占用
  4025. .alt($r('app.media.ic_avatar2'))
  4026. .clip(true)
  4027. .borderRadius({
  4028. topLeft: 12,
  4029. topRight: 12,
  4030. bottomLeft: 0,
  4031. bottomRight: 0
  4032. })
  4033. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4034. height: '99%' ,
  4035. dragBar: true,
  4036. onDisappear: () => {
  4037. this.longItemFilePath = '';
  4038. this.tempLyricContent = ''
  4039. },
  4040. showClose: true,
  4041. preferType: SheetType.CENTER ,
  4042. title: { title: '编辑标签' }
  4043. })
  4044. .draggable(false)
  4045. .opacity(this.opacityItem)// 绑定透明度
  4046. .animation({
  4047. duration: 666,
  4048. curve: 'ease-in-out' // 可选动画曲线
  4049. })
  4050. .margin({
  4051. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4052. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4053. })
  4054. Column() {
  4055. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4056. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4057. .maxLines(1)
  4058. .fontWeight(FontWeight.Bold)
  4059. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4060. .animation({
  4061. duration: 555,
  4062. curve: 'Linear',
  4063. })
  4064. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4065. height: '95%',
  4066. dragBar: true,
  4067. showClose: true,
  4068. onDisappear: () => {
  4069. this.longItemFilePathDetail = '';
  4070. },
  4071. blurStyle:BlurStyle.Thin,
  4072. backgroundColor:Color.Transparent,
  4073. preferType: SheetType.CENTER ,
  4074. title: { title: '详情' }
  4075. })
  4076. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4077. $r('app.color.text_color'))
  4078. Column() {
  4079. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4080. .fontSize(11)
  4081. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4082. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4083. .fontColor($r('app.color.text_color'))
  4084. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4085. .fontSize(11)
  4086. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4087. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4088. .fontColor($r('app.color.text_color'))
  4089. Row(){
  4090. Column(){
  4091. Text(item.md5Str?.includes('Lossless')?
  4092. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4093. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4094. .padding({ top: 3,right:6,left:6,bottom:3 })
  4095. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4096. $r('app.color.text_color'))
  4097. .fontWeight(500)
  4098. .borderRadius(12)
  4099. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4100. .backgroundColor('#FFC107')
  4101. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4102. }
  4103. .margin({ top: 2 ,right:6})
  4104. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4105. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4106. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4107. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  4108. .maxLines(1)
  4109. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4110. .margin({ top: 2})
  4111. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4112. || item.type == CommonConstants.TYPE_IS_ALBUM
  4113. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4114. .fontWeight(FontWeight.Medium)
  4115. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4116. $r('app.color.text_color'))
  4117. }
  4118. }
  4119. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4120. }
  4121. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  4122. .width(this.getGridWight())
  4123. .justifyContent(FlexAlign.Center)
  4124. .margin({
  4125. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4126. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4127. })
  4128. }
  4129. .width(this.getGridWight())
  4130. .borderRadius(12)
  4131. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  4132. .backgroundImageSize({ height: '100%', width: '100%' })
  4133. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4134. .animation({ curve: Curve.Sharp, duration: 300 })
  4135. Checkbox({ name: 'checkbox' + index })
  4136. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4137. .selectedColor(this.themeColor)
  4138. .shape(CheckBoxShape.CIRCLE)
  4139. .opacity(this.isMultiSelect ? 1 : 0)
  4140. .animation({
  4141. duration: 666,
  4142. curve: 'Smooth' // 可选动画曲线
  4143. })
  4144. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4145. Visibility.None)
  4146. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4147. .margin({ left: 20, top: 8, bottom: 8 })
  4148. .width(38)
  4149. .height(38)
  4150. }
  4151. }
  4152. .backgroundColor(Color.Transparent)
  4153. .width('100%')
  4154. .padding({ top: 15 })
  4155. .height(this.getGridAllHeight())
  4156. .onClick(() => {
  4157. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4158. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4159. this.handleFileSelection(item, !isChecked);
  4160. } else {
  4161. this.doPlay(item, index)
  4162. }
  4163. })
  4164. }
  4165. getGridAllHeight() {
  4166. let heightG = 222
  4167. switch (this.twoFingerType) {
  4168. case 1:
  4169. heightG = 143
  4170. break;
  4171. case 2:
  4172. heightG = 178
  4173. break;
  4174. case 3:
  4175. heightG = 222
  4176. break;
  4177. }
  4178. return heightG
  4179. }
  4180. getGridHeight() {
  4181. let heightG = 150
  4182. switch (this.twoFingerType) {
  4183. case 1:
  4184. heightG = 80
  4185. break;
  4186. case 2:
  4187. heightG = 110
  4188. break;
  4189. case 3:
  4190. heightG = 150
  4191. break;
  4192. }
  4193. return heightG
  4194. }
  4195. getGridWight() {
  4196. let wightG = 158
  4197. switch (this.twoFingerType) {
  4198. case 1:
  4199. wightG = 80
  4200. break;
  4201. case 2:
  4202. wightG = 110
  4203. break;
  4204. case 3:
  4205. wightG = 158
  4206. break;
  4207. }
  4208. return wightG
  4209. }
  4210. @State isShowDetail:boolean = false
  4211. @State longItemFilePathDetail:string =''
  4212. @Builder
  4213. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  4214. if(
  4215. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4216. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4217. item.name === LocalMusic.STR_HISTORY_MUSIC)
  4218. ){
  4219. //如果是专辑和艺术家的首页,不能长按
  4220. //如果是我的收藏 最近播放等也不能长按
  4221. }else{
  4222. Scroll() {
  4223. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  4224. Menu() {
  4225. MenuItem({
  4226. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  4227. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  4228. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  4229. })
  4230. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4231. .onClick(() => {
  4232. if (item) {
  4233. this.doFav(item)
  4234. }
  4235. this.longItemFilePath = ''
  4236. })
  4237. MenuItem({
  4238. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  4239. content: '下一首播放'
  4240. })
  4241. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4242. .onClick(() => {
  4243. this.addToNextPlay(item);
  4244. this.longItemFilePath = ''
  4245. })
  4246. MenuItem({
  4247. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  4248. content: '添加到歌单'
  4249. })
  4250. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4251. .onClick(async () => {
  4252. this.longItemFilePath = ''
  4253. await this.showAddToPlaylistDialog(item)
  4254. })
  4255. MenuItem({
  4256. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  4257. content: '编辑标签'
  4258. })
  4259. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  4260. height: '99%',
  4261. dragBar: true,
  4262. showClose: true,
  4263. preferType: SheetType.CENTER ,
  4264. title: { title: '编辑标签' }
  4265. })
  4266. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4267. .onClick(async() => {
  4268. this.setEditStrEmpty()
  4269. this.tempLyricContent = await this.getLyricContent(item);
  4270. if(this.isGridMusic||this.twoFingerType==4){
  4271. this.longItemFilePath = item.filePath
  4272. }else{
  4273. this.isShowEdit = !this.isShowEdit;
  4274. }
  4275. })
  4276. MenuItem({
  4277. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  4278. content: $r('app.string.select_all')
  4279. })
  4280. .onClick(() => {
  4281. this.isMultiSelect = !this.isMultiSelect
  4282. this.longItemFilePath = ''
  4283. this.selectedFiles.push(item)
  4284. })
  4285. MenuItem({
  4286. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  4287. content: $r('app.string.rename')
  4288. })
  4289. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4290. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4291. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4292. .onClick(() => {
  4293. this.showReNameDialog(item, index + '', filePath)
  4294. this.longItemFilePath = ''
  4295. })
  4296. MenuItem({
  4297. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  4298. content: $r('app.string.delete')
  4299. })
  4300. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4301. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4302. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4303. .onClick(() => {
  4304. this.selectedFiles.push(item)
  4305. this.showWarnIsDelete()
  4306. this.longItemFilePath = ''
  4307. })
  4308. MenuItem({
  4309. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  4310. content: $r('app.string.detail')
  4311. })
  4312. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  4313. height:'95%',
  4314. dragBar: true,
  4315. showClose: true,
  4316. blurStyle:BlurStyle.Thin,
  4317. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4318. backgroundColor:Color.Transparent,
  4319. title: { title: '详情信息' }
  4320. })
  4321. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4322. .onClick(() => {
  4323. if(this.isGridMusic||this.twoFingerType==4){
  4324. this.longItemFilePathDetail = item.filePath
  4325. }else{
  4326. this.isShowDetail = !this.isShowDetail
  4327. }
  4328. })
  4329. MenuItem({
  4330. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  4331. content: $r('app.string.share')
  4332. })
  4333. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4334. .onClick(() => {
  4335. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4336. this.longItemFilePath = ''
  4337. })
  4338. }
  4339. .font({ size: 15, weight: FontWeight.Normal })
  4340. }
  4341. .width(180)
  4342. }
  4343. .height('auto')
  4344. }
  4345. }
  4346. private listMaxScrollOffsetY: number = 0
  4347. @State selectedIndex: number = -1
  4348. setlistTwoFingers() {
  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 > 3) {
  4355. this.twoFingerType = 1
  4356. this.isGridMusic = true
  4357. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4358. }
  4359. } else {
  4360. this.twoFingerType--
  4361. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4362. if (this.twoFingerType < 1) {
  4363. this.twoFingerType = 4
  4364. this.columns = 1
  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. @Builder
  4373. getList(){
  4374. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  4375. this.getListView()
  4376. }
  4377. .pullDownRatio(this.ratioL)
  4378. .pullToRefresh(true)
  4379. .refreshOffset(0)
  4380. .onOffsetChange((offset: number) => {
  4381. // 越接近最大距离,下拉跟手系数越小。
  4382. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  4383. })
  4384. .onStateChange((refreshStatus: RefreshStatus) => {
  4385. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  4386. })
  4387. .onRefreshing(async () => {
  4388. if(this.modeType==0){
  4389. this.getHistoryList(false)
  4390. this.asyncCurrentPathOnlyFile()
  4391. }else if(this.modeType == 1){
  4392. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4393. }else if(this.modeType == 2){
  4394. workerInstance.postMessage({ code: 3, data: this.context });
  4395. }else if(this.modeType == 3){
  4396. workerInstance.postMessage({ code: 4, data: this.context });
  4397. }else if(this.modeType == 4){
  4398. this.doSongListTask()
  4399. }
  4400. console.log('onRefreshing test');
  4401. })
  4402. }
  4403. // 扫描当前目录下的文件,不扫描子目录
  4404. asyncCurrentPathOnlyFile(){
  4405. if(this.modeType==0){
  4406. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  4407. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  4408. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  4409. if(this.modeType==0){
  4410. this.getSortedFiles(this.currentPath)
  4411. }
  4412. setTimeout(() => {
  4413. this.isRefreshing = false;
  4414. }, 100)
  4415. }).catch((e:object)=>{
  4416. console.info("task1 catch e: " + e);
  4417. })
  4418. }
  4419. }
  4420. @Builder
  4421. getListView() {
  4422. List({ scroller: this.listScroller }) {
  4423. ListItemGroup({ header: this.coverHeader() }) {
  4424. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4425. ListItem() {
  4426. Column() {
  4427. if (item.type === CommonConstants.TYPE_IS_DIR
  4428. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  4429. this.DirItem(item, index)
  4430. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  4431. } else {
  4432. this.MusicItem(item, index)
  4433. }
  4434. }
  4435. .shadow(this.scaleItem === index ? {
  4436. radius: 70,
  4437. color: '#15000000',
  4438. offsetX: 0,
  4439. offsetY: 0
  4440. } :
  4441. {
  4442. radius: 0,
  4443. color: '#15000000',
  4444. offsetX: 0,
  4445. offsetY: 0
  4446. })
  4447. .animation({ curve: Curve.Sharp, duration: 300 })
  4448. }
  4449. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  4450. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  4451. .animation({ duration: 500 }),
  4452. TransitionEffect.scale({ x: 0, y: 0 })))
  4453. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4454. .swipeAction((
  4455. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  4456. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  4457. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  4458. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  4459. .onClick(() => {
  4460. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4461. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4462. this.handleFileSelection(item, !isChecked);
  4463. } else {
  4464. this.doPlay(item, index)
  4465. }
  4466. })
  4467. //拖动List关键代码开始
  4468. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4469. .zIndex(this.dragItem === index ? 1 : 0)
  4470. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4471. .gesture(
  4472. GestureGroup(GestureMode.Sequence,
  4473. LongPressGesture({ repeat: true })
  4474. .onAction((event?: GestureEvent) => {
  4475. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4476. this.scaleItem = index
  4477. })
  4478. })
  4479. .onActionEnd(() => {
  4480. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4481. this.scaleItem = -1
  4482. })
  4483. }),
  4484. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4485. .onActionStart(() => {
  4486. this.dragItem = index // 记录当前拖动项索引
  4487. this.dragRefOffset = 0 // 重置偏移基准
  4488. })
  4489. .onActionUpdate((event: GestureEvent) => {
  4490. this.offsetY = event.offsetY - this.dragRefOffset;
  4491. this.neighborItem = -1;
  4492. let indexA = this.videoLocalList.indexOf(item);
  4493. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4494. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4495. let value: number = 0;
  4496. if (this.offsetY < 0) {
  4497. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4498. this.neighborItem = indexA - 1;
  4499. this.neighborScale = 1 - value / 20;
  4500. } else if (this.offsetY > 0) {
  4501. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4502. this.neighborItem = indexA + 1;
  4503. this.neighborScale = 1 - value / 20;
  4504. }
  4505. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  4506. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4507. this.offsetY -= this.ITEM_INTV;
  4508. this.dragRefOffset += this.ITEM_INTV;
  4509. this.itemMove(indexA, indexA + 1);
  4510. });
  4511. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4512. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4513. this.offsetY += this.ITEM_INTV;
  4514. this.dragRefOffset -= this.ITEM_INTV;
  4515. this.itemMove(indexA, indexA - 1);
  4516. });
  4517. }
  4518. let curListOffset = this.listScroller.currentOffset()
  4519. // 获取手指信息
  4520. let fingerInfo = event.fingerList[0]
  4521. let clickPercentY =
  4522. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  4523. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  4524. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  4525. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  4526. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  4527. }
  4528. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  4529. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  4530. if (curListOffset.yOffset > scrollVelocity + 5) {
  4531. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  4532. }
  4533. }
  4534. })
  4535. .onActionEnd((event: GestureEvent) => {
  4536. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4537. this.dragItem = -1
  4538. this.neighborItem = -1
  4539. })
  4540. animateTo({
  4541. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4542. }, () => {
  4543. this.scaleItem = -1
  4544. })
  4545. })
  4546. )
  4547. .onCancel(() => {
  4548. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4549. this.dragItem = -1
  4550. this.neighborItem = -1
  4551. })
  4552. animateTo({
  4553. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4554. }, () => {
  4555. this.scaleItem = -1
  4556. })
  4557. })
  4558. ) //拖动List关键代码结束
  4559. }, (item: VideoItem) => item.filePath)
  4560. }
  4561. }
  4562. .scrollBar(BarState.Off)
  4563. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4564. .gesture(PinchGesture({ fingers: 2 })
  4565. .onActionEnd((event: GestureEvent) => {
  4566. this.setlistTwoFingers()
  4567. })
  4568. .onActionUpdate(e => {
  4569. this.scaleValue = this.pinchValue * e.scale
  4570. })
  4571. .onActionStart(e => {
  4572. }))
  4573. // .margin(
  4574. // this.isHiCar()&&(this.windowWidth>1800&&this.windowHeight>=1200)?{bottom:this.bottomBarHeight+98}:
  4575. // {
  4576. // bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  4577. // : (this.isShowCoverHeader() ? this.topBarHeight+35 :
  4578. // this.isHiCarSmall()||this.modeType==4?this.topBarHeight+90:this.topBarHeight+165)
  4579. // })
  4580. .margin({
  4581. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  4582. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  4583. })
  4584. .cachedCount(6)
  4585. .reuseId('list_item')
  4586. .borderRadius(20)
  4587. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4588. TransitionEffect.scale({ x: 0, y: 0 })))
  4589. .layoutWeight(1)
  4590. .onScrollIndex((start) => {
  4591. this.selectedIndex = start
  4592. })
  4593. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  4594. .lanes(
  4595. new BreakpointType<number>({
  4596. sm: 1,
  4597. md: 2,
  4598. lg: 2,
  4599. xl: 3,
  4600. xxl: 4
  4601. }).getValue(this.currentBreakpoint),
  4602. new BreakpointType<number>({
  4603. sm: 0,
  4604. md: 12,
  4605. lg: 12,
  4606. xl: 16,
  4607. xxl: 20
  4608. }).getValue(this.currentBreakpoint)
  4609. )
  4610. .onAreaChange((oldValue: Area, newValue: Area) => {
  4611. this.listArea = newValue
  4612. if (this.twoFingerType == 3) {
  4613. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  4614. } else if (this.twoFingerType == 2) {
  4615. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  4616. } else if (this.twoFingerType == 1) {
  4617. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  4618. }
  4619. })
  4620. .onScrollFrameBegin((offset: number) => {
  4621. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  4622. // if (this.isPhoneLan()) {
  4623. // this.setBarHeightHide(offset)
  4624. // } else
  4625. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4626. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4627. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4628. if (this.isScrollHide) {
  4629. this.setBarHeightHide2(offset)
  4630. } else {
  4631. this.setBarHeightNormal()
  4632. }
  4633. } else {
  4634. this.setBarHeightHide(offset)
  4635. }
  4636. return { offsetRemain: offset };
  4637. })
  4638. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  4639. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4640. .onDrop((event?: DragEvent) => {
  4641. try {
  4642. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4643. if (dragData !== undefined) {
  4644. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4645. if (records.length > 0) {
  4646. for (let i = 0; i < records.length; i++) {
  4647. let types = records[i].getTypes();
  4648. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4649. const fileUriUds =
  4650. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4651. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4652. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4653. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4654. this.targetFile = fileUriUds.oriUri;
  4655. this.saveVideoDatas([this.targetFile])
  4656. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4657. }
  4658. }
  4659. }
  4660. } else {
  4661. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4662. }
  4663. } else {
  4664. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4665. }
  4666. } catch (error) {
  4667. const err = error as BusinessError;
  4668. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4669. }
  4670. })
  4671. }
  4672. setBarHeightNormal() {
  4673. this.hideDone = false;
  4674. this.getUIContext().animateTo({
  4675. duration: 300
  4676. }, () => {
  4677. this.bottomBarHeight = 55 + 0;
  4678. this.topBarHeight = 50 + 0;
  4679. this.barOpacity = 1;
  4680. this.barBottomOpacity = 1
  4681. this.currentYOffset = 0;
  4682. this.isHiding = false;
  4683. });
  4684. }
  4685. setBarHeightHide(offset: number) {
  4686. if (offset > 0 && !this.hideDone) {
  4687. this.currentYOffset += offset;
  4688. if (this.currentYOffset <= 100) {
  4689. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  4690. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4691. this.barOpacity = 1 - this.currentYOffset / 100;
  4692. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  4693. } else {
  4694. this.topBarHeight = 0;
  4695. this.bottomBarHeight = 0;
  4696. this.barBottomOpacity = 0
  4697. this.barOpacity = 0;
  4698. this.hideDone = true;
  4699. }
  4700. this.isHiding = true;
  4701. }
  4702. if (offset < 0 && this.isHiding) {
  4703. this.hideDone = false;
  4704. this.getUIContext().animateTo({
  4705. duration: 300
  4706. }, () => {
  4707. this.bottomBarHeight = 55 + 0;
  4708. this.topBarHeight = 50 + 0;
  4709. this.barOpacity = 1;
  4710. this.barBottomOpacity = 1
  4711. this.currentYOffset = 0;
  4712. this.isHiding = false;
  4713. });
  4714. }
  4715. }
  4716. //这个方法没隐藏bottomBar,只隐藏topbar
  4717. setBarHeightHide2(offset: number) {
  4718. if (offset > 0 && !this.hideDone) {
  4719. this.currentYOffset += offset;
  4720. if (this.currentYOffset <= 100) {
  4721. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4722. this.barOpacity = 1 - this.currentYOffset / 100;
  4723. } else {
  4724. this.topBarHeight = 0;
  4725. this.barOpacity = 0;
  4726. this.hideDone = true;
  4727. }
  4728. this.isHiding = true;
  4729. }
  4730. if (offset < 0 && this.isHiding) {
  4731. this.hideDone = false;
  4732. this.getUIContext().animateTo({
  4733. duration: 300
  4734. }, () => {
  4735. this.topBarHeight = 50 + 0;
  4736. this.barOpacity = 1;
  4737. this.currentYOffset = 0;
  4738. this.isHiding = false;
  4739. });
  4740. }
  4741. }
  4742. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  4743. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  4744. switch (item.type) {
  4745. case CommonConstants.TYPE_IS_DIR:
  4746. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  4747. let offsetB = 0
  4748. if(this.twoFingerType==4){
  4749. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4750. let cur = this.waterScroller.currentOffset()
  4751. if (cur && typeof cur.yOffset === 'number') {
  4752. offsetB = cur.yOffset
  4753. }
  4754. }
  4755. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  4756. }else
  4757. if (this.isGridMusic) {
  4758. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4759. let cur = this.scroller.currentOffset()
  4760. if (cur && typeof cur.yOffset === 'number') {
  4761. offsetB = cur.yOffset
  4762. }
  4763. }
  4764. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  4765. } else {
  4766. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4767. let cur = this.listScroller.currentOffset()
  4768. if (cur && typeof cur.yOffset === 'number') {
  4769. offsetB = cur.yOffset
  4770. }
  4771. }
  4772. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  4773. }
  4774. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  4775. this.showVerifyDialog()
  4776. this.currentTitleName = '私密音频'
  4777. this.currentTitleCover = $r('app.media.ic_avatar5')
  4778. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  4779. this.titleBarModel.setTitleName('最近播放')
  4780. this.currentTitleCover = $r('app.media.ic_avatar2')
  4781. this.currentTitleName = '最近播放'
  4782. //加载动画效果
  4783. this.updateListData(this.historyList, true)
  4784. // this.videoLocalList = this.historyList
  4785. if (ArrayUtil.isEmpty(this.historyList)) {
  4786. ToastUtil.showToast('最近播放记录空空如也')
  4787. } else {
  4788. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  4789. }
  4790. this.isHistory = true
  4791. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4792. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  4793. this.titleBarModel.setTitleName('我的收藏')
  4794. this.currentTitleName = '我的收藏'
  4795. this.currentTitleCover = $r('app.media.ic_avatar1')
  4796. //加载动画效果
  4797. this.updateListData(this.favList)
  4798. if (ArrayUtil.isEmpty(this.favList)) {
  4799. ToastUtil.showToast('无音乐收藏记录')
  4800. } else {
  4801. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  4802. }
  4803. this.isFavMusic = true
  4804. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4805. } else {
  4806. this.currentTitleName = item.name
  4807. this.currentPath = item.filePath
  4808. this.currentTitleCover = $r('app.media.ic_avatar5')
  4809. this.getSortedFiles(this.currentPath)
  4810. }
  4811. //进入歌单的时候的滚动位置在顶部
  4812. if(this.twoFingerType==4){
  4813. setTimeout(() => {
  4814. this.waterScroller.scrollEdge(Edge.Top)
  4815. this.scroller.scrollEdge(Edge.Top)
  4816. }, 380)
  4817. }else{
  4818. if (this.isGridMusic) {
  4819. this.scroller.scrollEdge(Edge.Top)
  4820. }else{
  4821. this.listScroller.scrollEdge(Edge.Top)
  4822. }
  4823. }
  4824. break;
  4825. case CommonConstants.TYPE_IS_ARTIST:
  4826. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  4827. let offsetA = 0
  4828. if(this.twoFingerType==4){
  4829. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4830. let cur = this.waterScroller.currentOffset()
  4831. if (cur && typeof cur.yOffset === 'number') {
  4832. offsetA = cur.yOffset
  4833. }
  4834. }
  4835. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  4836. }else
  4837. if (this.isGridMusic) {
  4838. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4839. let cur = this.scroller.currentOffset()
  4840. if (cur && typeof cur.yOffset === 'number') {
  4841. offsetA = cur.yOffset
  4842. }
  4843. }
  4844. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  4845. } else {
  4846. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4847. let cur = this.listScroller.currentOffset()
  4848. if (cur && typeof cur.yOffset === 'number') {
  4849. offsetA = cur.yOffset
  4850. }
  4851. }
  4852. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  4853. }
  4854. let mList = this.artistMap.get(item.name)
  4855. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  4856. Utility.doSortListAscending(mList)
  4857. this.isCanBack = true
  4858. this.titleBarModel.setTitleName(item.name)
  4859. this.currentTitleName = '艺术家:' + item.name
  4860. if (item.pixelMapPath) {
  4861. this.currentTitleCover = item.pixelMapPath
  4862. }
  4863. this.updateListData(mList)
  4864. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4865. }
  4866. //进入歌单的时候的滚动位置在顶部
  4867. if(this.twoFingerType==4){
  4868. setTimeout(() => {
  4869. this.waterScroller.scrollEdge(Edge.Top)
  4870. this.scroller.scrollEdge(Edge.Top)
  4871. }, 380)
  4872. }else{
  4873. if (this.isGridMusic) {
  4874. this.scroller.scrollEdge(Edge.Top)
  4875. }else{
  4876. this.listScroller.scrollEdge(Edge.Top)
  4877. }
  4878. }
  4879. break;
  4880. case CommonConstants.TYPE_IS_ALBUM:
  4881. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  4882. let offset = 0
  4883. if(this.twoFingerType==4){
  4884. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4885. let cur = this.waterScroller.currentOffset()
  4886. if (cur && typeof cur.yOffset === 'number') {
  4887. offset = cur.yOffset
  4888. }
  4889. }
  4890. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  4891. }else
  4892. if (this.isGridMusic) {
  4893. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4894. let cur = this.scroller.currentOffset()
  4895. if (cur && typeof cur.yOffset === 'number') {
  4896. offset = cur.yOffset
  4897. }
  4898. }
  4899. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  4900. } else {
  4901. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4902. let cur = this.listScroller.currentOffset()
  4903. if (cur && typeof cur.yOffset === 'number') {
  4904. offset = cur.yOffset
  4905. }
  4906. }
  4907. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4908. }
  4909. let albumList = this.albumMap.get(item.name)
  4910. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4911. Utility.doSortListAscending(albumList)
  4912. this.isCanBack = true
  4913. this.titleBarModel.setTitleName(item.name)
  4914. this.currentTitleName = '专辑:' + item.name
  4915. if (item.pixelMapPath) {
  4916. this.currentTitleCover = item.pixelMapPath
  4917. }
  4918. this.updateListData(albumList)
  4919. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4920. this.mScrollMap.set(item.name, this.selectedIndex)
  4921. }
  4922. //进入歌单的时候的滚动位置在顶部
  4923. if(this.twoFingerType==4){
  4924. setTimeout(() => {
  4925. this.waterScroller.scrollEdge(Edge.Top)
  4926. this.scroller.scrollEdge(Edge.Top)
  4927. }, 380)
  4928. }else{
  4929. if (this.isGridMusic) {
  4930. this.scroller.scrollEdge(Edge.Top)
  4931. }else{
  4932. this.listScroller.scrollEdge(Edge.Top)
  4933. }
  4934. }
  4935. break;
  4936. case CommonConstants.TYPE_IS_CSJAD:
  4937. return
  4938. break;
  4939. case CommonConstants.TYPE_LOCAL:
  4940. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  4941. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  4942. const cueTracks:CueTrack[] = cueinfo.tracks
  4943. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  4944. if(ArrayUtil.isNotEmpty(cueTracks)){
  4945. this.showCueDialog(cueTracks,cueinfo)
  4946. }
  4947. // this.showCueSheet = !this.showCueSheet
  4948. return
  4949. }
  4950. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4951. this.stop();
  4952. }
  4953. if (isOpen) {
  4954. this.currentSong = item
  4955. if (index !== undefined) {
  4956. this.curIndex = index
  4957. }
  4958. this.songList = []
  4959. this.songList.push(item)
  4960. this.sonDataSource.pushArrayData(this.songList)
  4961. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  4962. this.currentSong = item
  4963. if (index !== undefined) {
  4964. this.curIndex = index
  4965. }
  4966. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  4967. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  4968. }else {
  4969. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4970. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4971. this.songList = globalVideoList
  4972. this.sonDataSource.pushArrayData(this.songList)
  4973. this.currentSong = globalVideoList[this.curIndex]
  4974. }
  4975. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  4976. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  4977. this.name = this.currentSong.name
  4978. this.cover = this.currentSong.pixelMapPath
  4979. this.artist = this.currentSong.artist
  4980. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  4981. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  4982. this.startPlayOrResumePlay()
  4983. break;
  4984. case CommonConstants.TYPE_WEBDAV:
  4985. // 处理网络音频播放(WebDAV)
  4986. Logger.info(`heanup 处理网络音频播放: ${item.name}, URL: ${item.filePath}`)
  4987. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4988. this.stop();
  4989. }
  4990. if (isOpen) {
  4991. this.currentSong = item
  4992. if (index !== undefined) {
  4993. this.curIndex = index
  4994. }
  4995. this.songList = []
  4996. this.songList.push(item)
  4997. this.sonDataSource.pushArrayData(this.songList)
  4998. } else if (isFromSonPlayList) {
  4999. // 点击来自右下角的播放列表
  5000. this.currentSong = item
  5001. if (index !== undefined) {
  5002. this.curIndex = index
  5003. }
  5004. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5005. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5006. } else {
  5007. // 从全局网络音频列表中查找
  5008. let globalVideoList = this.videoLocalList.filter(video => video.type === CommonConstants.TYPE_WEBDAV) as VideoItem[];
  5009. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  5010. if (this.curIndex === -1 && index !== undefined) {
  5011. this.curIndex = index;
  5012. }
  5013. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  5014. this.currentSong = this.songList[this.curIndex];
  5015. this.sonDataSource.pushArrayData(this.songList)
  5016. }
  5017. AppStorage.setOrCreate('currentSong', this.currentSong);
  5018. // 对WebDAV URL进行编码处理,确保空格等特殊字符被正确编码
  5019. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  5020. this.name = this.currentSong.name
  5021. this.cover = this.currentSong.pixelMapPath
  5022. this.artist = this.currentSong.artist
  5023. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 编码后URL: ${this.videoUrl}`)
  5024. this.startPlayOrResumePlay()
  5025. break;
  5026. }
  5027. }
  5028. private cueComponentId: number = 0
  5029. //显示cue分轨列表对话框
  5030. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  5031. this.getUIContext().getPromptAction().openCustomDialog({
  5032. builder: () => {
  5033. this.cueComptentBuilder(cueTracks,cueinfo)
  5034. },
  5035. isModal:true,
  5036. showInSubWindow:false,
  5037. maskColor: Color.Transparent,
  5038. dialogTransition: // 设置弹窗内容显示的过渡效果
  5039. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  5040. .animation({ duration: 600, curve: Curve.Smooth }),
  5041. maskTransition: // 设置蒙层显示的过渡效果
  5042. TransitionEffect.opacity(0.5)
  5043. .animation({ duration: 600, curve: Curve.Smooth })
  5044. }).then((dialogId: number) => {
  5045. this.cueComponentId = dialogId
  5046. })
  5047. .catch((error: BusinessError) => {
  5048. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5049. })
  5050. }
  5051. @Builder
  5052. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  5053. CueComptent({
  5054. title:cueinfo.title,
  5055. cueTracks:cueTracks,
  5056. isLongNameRoLL:this.isLongNameRoLL,
  5057. onCancel:()=>{
  5058. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  5059. },
  5060. onDoItemClick:(item: CueTrack, index: number)=>{
  5061. //获取cueinfo对应的filePath
  5062. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5063. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  5064. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  5065. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  5066. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  5067. if (this.currentSong){
  5068. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5069. this.stop();//播放之前先停止之前播放。
  5070. }
  5071. this.songList = globalVideoList
  5072. this.sonDataSource.pushArrayData(this.songList)
  5073. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  5074. this.name = item.title||this.currentSong.name
  5075. this.cover = this.currentSong.pixelMapPath
  5076. this.artist = item.performer||this.currentSong.artist
  5077. this.currentSong.name = this.name
  5078. this.currentSong.artist = this.artist
  5079. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5080. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  5081. }
  5082. }
  5083. })
  5084. }
  5085. @Builder
  5086. PlayController() {
  5087. Column() {
  5088. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  5089. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5090. Row() {
  5091. if(this.isHiCar()){
  5092. this.playConRigth()
  5093. Column(){
  5094. this.centerName()
  5095. }.layoutWeight(1)
  5096. .onClick(()=>{
  5097. this.showPlayerView()
  5098. })
  5099. this.playConLeft(false)
  5100. }else{
  5101. this.playConLeft()
  5102. this.playConRigth()
  5103. }
  5104. }
  5105. .width('100%')
  5106. .height(this.bottomBarHeight)
  5107. .justifyContent(FlexAlign.Center)
  5108. .hitTestBehavior(HitTestMode.Transparent)
  5109. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  5110. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  5111. // modalTransition: ModalTransition.DEFAULT,
  5112. transition: AnimationHelper.transitionInDown(666),
  5113. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  5114. })
  5115. .padding({
  5116. left: 16,
  5117. right: 16
  5118. })
  5119. Line()
  5120. .width('100%')
  5121. .height(25)
  5122. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  5123. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5124. }
  5125. .clickEffect({ level: ClickEffectLevel.HEAVY })
  5126. }
  5127. @State isFrontWhite: boolean = false
  5128. @Builder
  5129. centerName() {
  5130. Column() {
  5131. Text(this.currentSong?.name)
  5132. .fontSize(16)
  5133. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5134. .maxLines(1)
  5135. .fontColor($r('app.color.text_color'))
  5136. .fontWeight(500);
  5137. Row() {
  5138. Text(this.currentSong?.artist)
  5139. .margin({ top: 2 })
  5140. .fontSize(13)
  5141. .textAlign(TextAlign.Start)
  5142. .maxLines(1)
  5143. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5144. .fontColor($r('app.color.text_color'));
  5145. }
  5146. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5147. }
  5148. .alignItems(HorizontalAlign.Center)
  5149. }
  5150. @Builder
  5151. playConLeft(isLeft: boolean = true) {
  5152. Row() {
  5153. RotatingCover({ songLabel: this.currentSong?.pixelMapPath });
  5154. Column() {
  5155. Text(this.currentSong?.name)
  5156. .fontSize(16)
  5157. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5158. .maxLines(1)
  5159. .fontColor($r('app.color.text_color'))
  5160. .fontWeight(500);
  5161. Row() {
  5162. Text(this.currentSong?.artist)
  5163. .margin({ top: 2 })
  5164. .fontSize(13)
  5165. .textAlign(TextAlign.Start)
  5166. .maxLines(1)
  5167. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5168. .fontColor($r('app.color.text_color'));
  5169. }
  5170. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5171. }
  5172. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  5173. .margin({ right: isLeft?22:10 })
  5174. .visibility(isLeft? Visibility.Visible:Visibility.None)
  5175. }
  5176. .padding({ right: 18 })
  5177. .layoutWeight(isLeft?1:0)
  5178. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5179. .onClick(() => {
  5180. this.showPlayerView()
  5181. })
  5182. }
  5183. //打开播放页
  5184. showPlayerView() {
  5185. if (ArrayUtil.isNotEmpty(this.songList)) {
  5186. this.isShowPlay = true;
  5187. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  5188. this.initLyric(lyricPath);
  5189. this.startAutoHide();
  5190. } else {
  5191. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  5192. }
  5193. }
  5194. @Builder
  5195. playConRigth() {
  5196. Row() {
  5197. Image($r('app.media.hm_previous'))
  5198. .height(28)
  5199. .width(28)
  5200. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5201. .margin({ left: 8, right: 16 })
  5202. .fillColor(this.themeColor)
  5203. .displayPriority(2)
  5204. .onClick(() => {
  5205. if (ArrayUtil.isNotEmpty(this.songList)) {
  5206. this.playPrevious()
  5207. } else {
  5208. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5209. }
  5210. })
  5211. //播放进度条
  5212. Stack() {
  5213. Progress({
  5214. value: Math.floor(this.progressValue),
  5215. type: ProgressType.Ring,
  5216. })
  5217. .color(this.themeColor)// 进度条前景色为灰色
  5218. .backgroundColor($r('app.color.index_background'))
  5219. .height(40)
  5220. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5221. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  5222. .height(38)
  5223. .width(38)
  5224. .displayPriority(3)
  5225. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5226. .fillColor(this.themeColor)
  5227. .onClick(() => {
  5228. if (ArrayUtil.isNotEmpty(this.songList)) {
  5229. console.info('onecold playOrPause 4642')
  5230. this.playOrPause()
  5231. } else {
  5232. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5233. }
  5234. })
  5235. }
  5236. Image($r('app.media.hm_next'))
  5237. .height(28)
  5238. .width(28)
  5239. .margin({
  5240. right: 16,
  5241. left: 16
  5242. })
  5243. .fillColor(this.themeColor)
  5244. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5245. .displayPriority(2)
  5246. .onClick(() => {
  5247. if (ArrayUtil.isNotEmpty(this.songList)) {
  5248. this.playNext()
  5249. } else {
  5250. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5251. }
  5252. })
  5253. Image($r('app.media.hm_playlist'))
  5254. .height(28)
  5255. .width(28)
  5256. .displayPriority(1)
  5257. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5258. .fillColor(this.themeColor)
  5259. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  5260. height: '95%',
  5261. dragBar: true,
  5262. showClose: true,
  5263. blurStyle: BlurStyle.Thin,
  5264. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5265. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  5266. title: {
  5267. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5268. + `(${this.songList.length}首)`
  5269. }
  5270. })
  5271. .onClick(() => {
  5272. if (ArrayUtil.isNotEmpty(this.songList)) {
  5273. this.isShowSheet = !this.isShowSheet;
  5274. this.isFrontWhite = false
  5275. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  5276. this.scrollIndex()
  5277. } else {
  5278. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5279. }
  5280. })
  5281. }
  5282. }
  5283. scrollIndex(){
  5284. try {
  5285. setTimeout(() => {
  5286. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  5287. if(this.curIndex>60){
  5288. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  5289. }else{
  5290. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5291. }
  5292. })
  5293. }, 123)
  5294. }catch (error) {
  5295. console.error(`onecold scrollIndex出错: ${error}`);
  5296. }
  5297. }
  5298. //播放列表布局
  5299. @Builder
  5300. PlayListSheet() {
  5301. Column() {
  5302. this.PlayList()
  5303. }
  5304. .width('100%')
  5305. .height('100%')
  5306. }
  5307. @State titleStr: string = ''
  5308. @State ablumStr: string = ''
  5309. @State artistStr: string = ''
  5310. @State lyricConStr: string = ''
  5311. @State currentEditItem: string = ''
  5312. @State yearStr: string = ''
  5313. @State trackStr: string = ''
  5314. @State genreStr: string = ''
  5315. @State imagePathStr: string = ''
  5316. @State albumArtistStr: string = ''
  5317. @State composerStr: string = ''
  5318. @State lyricistStr: string = ''
  5319. @State commentStr: string = ''
  5320. @State discStr: string = ''
  5321. doUpdateData() {
  5322. setTimeout(() => {
  5323. if (this.modeType === 0) {
  5324. this.deleteCache(this.currentPath)
  5325. this.getSortedFiles(this.currentPath)
  5326. }
  5327. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5328. workerInstance.postMessage({ code: 3, data: this.context });
  5329. workerInstance.postMessage({ code: 4, data: this.context });
  5330. }, 999)
  5331. }
  5332. //编辑信息
  5333. async doEdit(item: VideoItem) {
  5334. if (!item) {
  5335. return
  5336. }
  5337. if (StrUtil.isEmpty(this.titleStr)) {
  5338. ToastUtil.showToast('标题不能为空')
  5339. return
  5340. }
  5341. //用户更改了封面,那就内嵌下封面
  5342. if(StrUtil.isNotEmpty(this.imagePathStr)){
  5343. const resultCover:boolean = await changeMusicCover(this.context,
  5344. item.filePath,this.imagePathStr,true);
  5345. this.imagePathStr = ''
  5346. if(resultCover){
  5347. ToastUtil.showToast('内嵌封面成功')
  5348. }
  5349. }
  5350. const metadata:FFMpegTags = {
  5351. title: this.titleStr,
  5352. artist: this.artistStr,
  5353. album: this.ablumStr,
  5354. TYER:this.yearStr,
  5355. genre:this.genreStr,
  5356. track:this.trackStr,
  5357. album_artist:this.albumArtistStr,
  5358. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  5359. COMPOSER:this.composerStr,
  5360. lyricist:this.lyricistStr,
  5361. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  5362. comment:this.commentStr,
  5363. disc:this.discStr,
  5364. };
  5365. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  5366. const result:boolean = await repairAudioMetadata(
  5367. item.filePath,
  5368. this.lyricConStr,
  5369. metadata,
  5370. true
  5371. );
  5372. if (result) {
  5373. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  5374. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  5375. (success: boolean, error?: string) => {
  5376. // this.isShowEdit = false
  5377. if (success) {
  5378. console.log(" onecold 编辑信息成功,数据库已同步");
  5379. ToastUtil.showToast('内嵌音乐标签成功')
  5380. this.isShowMoreView = false
  5381. this.name = this.titleStr
  5382. if (item.filePath == this.currentSong?.filePath) {
  5383. this.currentSong.name = this.titleStr
  5384. this.artist = this.artistStr
  5385. this.currentSong.artist = this.artistStr
  5386. this.currentSong.album = this.ablumStr
  5387. this.currentSong.year = this.yearStr
  5388. this.currentSong.genre = this.genreStr
  5389. this.currentSong.track = this.trackStr
  5390. this.currentSong.lyricContent = this.lyricConStr
  5391. this.initLyric(item.filePath)
  5392. this.currentSong.ALBUMARTIST = this.albumArtistStr
  5393. this.currentSong.COMPOSER = this.composerStr
  5394. this.currentSong.LYRICIST = this.lyricistStr
  5395. this.currentSong.COMMENT = this.commentStr
  5396. }
  5397. this.doUpdateData()
  5398. } else {
  5399. // ToastUtil.showToast('保存失败' + error?.toString())
  5400. console.error(" onecold 编辑信息数据库失败原因: " + error);
  5401. }
  5402. });
  5403. console.log(' onecold 元数据标签更新成功,');
  5404. } else {
  5405. ToastUtil.showToast('内嵌音乐标签失败')
  5406. console.log('onecold 内嵌音乐标签失败');
  5407. }
  5408. this.longItemFilePath = ''
  5409. this.tempLyricContent = ''
  5410. this.isShowEdit = false
  5411. }
  5412. updateLyricToDB() {
  5413. }
  5414. @Builder
  5415. editSheet(item: VideoItem) {
  5416. Scroll() {
  5417. Column() {
  5418. this.editDetail(item)
  5419. }
  5420. }
  5421. .width('100%')
  5422. .height('100%')
  5423. }
  5424. @Builder
  5425. editDetail(item: VideoItem) {
  5426. Column() {
  5427. if (item) {
  5428. Row() {
  5429. Stack() {
  5430. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  5431. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  5432. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  5433. item.pixelMapPath)
  5434. .fillColor(this.themeColor)
  5435. .height(88)
  5436. .width(88)
  5437. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5438. .borderRadius(12)
  5439. .clip(true)
  5440. .opacity(this.opacityItem)// 绑定透明度
  5441. .margin({ left: 25 })
  5442. }
  5443. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5444. .onClick(async () => {
  5445. const imagePath:string | undefined = await this.goSelectImage(item);
  5446. if (imagePath) {
  5447. //用户更改过图片
  5448. this.imagePathStr = imagePath
  5449. }
  5450. })
  5451. .width('28%')
  5452. Row() {
  5453. Column() {
  5454. Text(item.name)
  5455. .fontSize(17)
  5456. .maxLines(1)
  5457. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5458. .animation({
  5459. duration: 555,
  5460. curve: 'Linear',
  5461. })
  5462. .fontColor(this.themeColor)
  5463. .margin({ left: 8 })
  5464. Row() {
  5465. Text(item.artist)
  5466. .fontSize(14)
  5467. .maxLines(1)
  5468. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5469. .padding({ top: 8 })
  5470. .fontColor(this.themeColor)
  5471. .margin({ left: 8 })
  5472. }
  5473. }
  5474. .height('100%')
  5475. .width(100)
  5476. .layoutWeight(1)
  5477. .justifyContent(FlexAlign.Center)
  5478. .alignItems(HorizontalAlign.Start)
  5479. Column() {
  5480. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5481. Row(){
  5482. SymbolGlyph($r('sys.symbol.picture'))
  5483. .fontSize(18)
  5484. .fontColor([Color.White])
  5485. Text('获取封面')
  5486. .margin({ left: 4 })
  5487. .fontSize(11)
  5488. .fontColor(Color.White)
  5489. .fontWeight(480)
  5490. .textAlign(TextAlign.Center)
  5491. }
  5492. .justifyContent(FlexAlign.Center)
  5493. }
  5494. .height(38)
  5495. .width(100)
  5496. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5497. .backgroundColor(this.themeColor)
  5498. .stateEffect(true)
  5499. .margin({ right: 35 })
  5500. .onClick(async () => {
  5501. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  5502. this.showTipsDialog();
  5503. return; // Return empty string when no API is configured
  5504. }
  5505. const imagePath:string | undefined = await this.doSearchCover(item);
  5506. console.info('onecold imagePath = '+imagePath)
  5507. if (StrUtil.isNotEmpty(imagePath)) {
  5508. //用户更改过图片
  5509. this.imagePathStr = imagePath
  5510. ToastUtil.showToast('获取封面成功')
  5511. }else{
  5512. ToastUtil.showToast('获取封面失败,请重试')
  5513. }
  5514. })
  5515. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5516. Row(){
  5517. SymbolGlyph($r('sys.symbol.input_mode'))
  5518. .fontSize(18)
  5519. .fontColor([Color.White])
  5520. Text('获取歌词')
  5521. .margin({ left: 4 })
  5522. .fontSize(11)
  5523. .fontColor(Color.White)
  5524. .fontWeight(480)
  5525. .textAlign(TextAlign.Center)
  5526. }
  5527. .justifyContent(FlexAlign.Center)
  5528. }
  5529. .height(38)
  5530. .width(100)
  5531. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5532. .backgroundColor(this.themeColor)
  5533. .stateEffect(true)
  5534. .margin({ top: 9, right: 35 })
  5535. .onClick(async () => {
  5536. //判断有没有设置api
  5537. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  5538. if (StrUtil.isEmpty(apiUrl)) {
  5539. this.isLyricSetting = false
  5540. this.showTipsDialog()
  5541. return
  5542. }
  5543. let artist = item.artist
  5544. let title = item.name
  5545. if(!artist)
  5546. artist = ''
  5547. if(!title)
  5548. title = ''
  5549. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  5550. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5551. this.lyricConStr = res;
  5552. ToastUtil.showToast('获取歌词成功')
  5553. }else{
  5554. ToastUtil.showToast('获取歌词失败,请重试')
  5555. }
  5556. })
  5557. }
  5558. .justifyContent(FlexAlign.Start)
  5559. }
  5560. .height('100%')
  5561. .justifyContent(FlexAlign.Start)
  5562. .layoutWeight(1)
  5563. }
  5564. .width('100%')
  5565. .height(98)
  5566. Row() {
  5567. Text('标题:')
  5568. .fontSize(14)
  5569. .fontColor($r('app.color.text_color'))
  5570. .margin({ left: 22 })
  5571. TextInput({ text: item.name })
  5572. .height(40)
  5573. .maxLines(1)
  5574. .fontSize(14)
  5575. .layoutWeight(1)
  5576. .fontColor($r('app.color.text_color'))
  5577. .margin({ right: 20, left: 10 })
  5578. .onChange((val: string) => {
  5579. this.titleStr = val
  5580. })
  5581. }
  5582. .width('100%')
  5583. .margin({ top: 10, bottom: 10 })
  5584. .justifyContent(FlexAlign.Start)
  5585. Row() {
  5586. Text('艺术家:')
  5587. .fontSize(14)
  5588. .fontColor($r('app.color.text_color'))
  5589. .margin({ left: 22 })
  5590. TextInput({ text: item.artist })
  5591. .height(40)
  5592. .maxLines(1)
  5593. .fontSize(14)
  5594. .layoutWeight(1)
  5595. .fontColor($r('app.color.text_color'))
  5596. .margin({ right: 20, left: 10 })
  5597. .onChange((val: string) => {
  5598. this.artistStr = val
  5599. })
  5600. }
  5601. .width('100%')
  5602. .margin({ top: 10, bottom: 10 })
  5603. .justifyContent(FlexAlign.Start)
  5604. Row() {
  5605. Text('专辑名:')
  5606. .fontSize(14)
  5607. .fontColor($r('app.color.text_color'))
  5608. .margin({ left: 22 })
  5609. TextInput({ text: item.album })
  5610. .height(40)
  5611. .maxLines(1)
  5612. .fontSize(14)
  5613. .layoutWeight(1)
  5614. .fontColor($r('app.color.text_color'))
  5615. .margin({ right: 20, left: 10 })
  5616. .onChange((val: string) => {
  5617. this.ablumStr = val
  5618. })
  5619. }
  5620. .width('100%')
  5621. .margin({ top: 10, bottom: 10 })
  5622. .justifyContent(FlexAlign.Start)
  5623. Row() {
  5624. Column(){
  5625. Column(){
  5626. Text('歌词:')
  5627. .fontSize(14)
  5628. .fontColor($r('app.color.text_color'))
  5629. .margin({ top:9,left: 22 })
  5630. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5631. SymbolGlyph($r('sys.symbol.trash_fill'))
  5632. .fontSize(25)
  5633. .alignSelf(ItemAlign.Center)
  5634. .margin({ left: 22,top:25})
  5635. }
  5636. .backgroundColor(Color.Transparent)
  5637. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5638. Visibility.None:Visibility.Visible)
  5639. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5640. .onClick(()=>{
  5641. this.lyricConStr = ''
  5642. this.lyricContent = ''
  5643. this.tempLyricContent = ''
  5644. })
  5645. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5646. SymbolGlyph($r('sys.symbol.plus'))
  5647. .fontSize(25)
  5648. .alignSelf(ItemAlign.Center)
  5649. .margin({ left: 22,top:25})
  5650. }
  5651. .backgroundColor(Color.Transparent)
  5652. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5653. .onClick( ()=>{
  5654. this.callFilePickerSelectFileForLyric()
  5655. })
  5656. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5657. SymbolGlyph($r('sys.symbol.traditional_square'))
  5658. .fontSize(25)
  5659. .alignSelf(ItemAlign.Center)
  5660. .margin({ left: 22,top:25})
  5661. }
  5662. .backgroundColor(Color.Transparent)
  5663. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5664. Visibility.None:Visibility.Visible)
  5665. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5666. .onClick( ()=>{
  5667. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5668. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  5669. })
  5670. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5671. Image($r('app.media.jianti'))
  5672. .height(25)
  5673. .fillColor($r('app.color.text_color'))
  5674. .alignSelf(ItemAlign.Center)
  5675. .margin({ left: 22,top:25})
  5676. }
  5677. .backgroundColor(Color.Transparent)
  5678. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5679. Visibility.None:Visibility.Visible)
  5680. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5681. .onClick( ()=>{
  5682. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5683. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  5684. })
  5685. }
  5686. .layoutWeight(1)
  5687. }
  5688. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  5689. this.tempLyricContent })
  5690. .type(TextAreaType.NORMAL)
  5691. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  5692. .fontSize(14)
  5693. .layoutWeight(1)
  5694. .fontColor($r('app.color.text_color'))
  5695. .margin({ right: 20, left: 10 })
  5696. .onChange((val: string) => {
  5697. this.lyricConStr = val
  5698. })
  5699. }
  5700. .width('100%')
  5701. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  5702. .margin({ top: 10, bottom: 10 })
  5703. .justifyContent(FlexAlign.Start)
  5704. Row() {
  5705. Text('年份:')
  5706. .fontSize(14)
  5707. .fontColor($r('app.color.text_color'))
  5708. .margin({ left: 22 })
  5709. TextInput({ text: item.year })
  5710. .height(40)
  5711. .maxLines(1)
  5712. .fontSize(14)
  5713. .type(InputType.Number)
  5714. .layoutWeight(1)
  5715. .fontColor($r('app.color.text_color'))
  5716. .margin({ right: 20, left: 10 })
  5717. .onChange((val: string) => {
  5718. this.yearStr = val
  5719. })
  5720. }
  5721. .width('100%')
  5722. .margin({ top: 10, bottom: 10 })
  5723. .justifyContent(FlexAlign.Start)
  5724. Row() {
  5725. Text('音轨号:')
  5726. .fontSize(14)
  5727. .fontColor($r('app.color.text_color'))
  5728. .margin({ left: 22 })
  5729. TextInput({ text:item.track=='未知'?'': item.track })
  5730. .height(40)
  5731. .maxLines(1)
  5732. .fontSize(14)
  5733. .type(InputType.Number)
  5734. .layoutWeight(1)
  5735. .fontColor($r('app.color.text_color'))
  5736. .margin({ right: 20, left: 10 })
  5737. .onChange((val: string) => {
  5738. this.trackStr = val
  5739. })
  5740. }
  5741. .width('100%')
  5742. .margin({ top: 10, bottom: 10 })
  5743. .justifyContent(FlexAlign.Start)
  5744. Row() {
  5745. Text('碟号:')
  5746. .fontSize(14)
  5747. .fontColor($r('app.color.text_color'))
  5748. .margin({ left: 22 })
  5749. TextInput({ text:item.disc })
  5750. .height(40)
  5751. .maxLines(1)
  5752. .fontSize(14)
  5753. .type(InputType.Number)
  5754. .layoutWeight(1)
  5755. .fontColor($r('app.color.text_color'))
  5756. .margin({ right: 20, left: 10 })
  5757. .onChange((val: string) => {
  5758. this.discStr = val
  5759. })
  5760. }
  5761. .width('100%')
  5762. .margin({ top: 10, bottom: 10 })
  5763. .justifyContent(FlexAlign.Start)
  5764. Row() {
  5765. Text('风格:')
  5766. .fontSize(14)
  5767. .fontColor($r('app.color.text_color'))
  5768. .margin({ left: 22 })
  5769. TextInput({ text: item.genre })
  5770. .height(40)
  5771. .maxLines(1)
  5772. .fontSize(14)
  5773. .layoutWeight(1)
  5774. .fontColor($r('app.color.text_color'))
  5775. .margin({ right: 20, left: 10 })
  5776. .onChange((val: string) => {
  5777. this.genreStr = val
  5778. })
  5779. }
  5780. .width('100%')
  5781. .margin({ top: 10, bottom: 10 })
  5782. .justifyContent(FlexAlign.Start)
  5783. Row() {
  5784. Text('专辑艺术家:')
  5785. .fontSize(14)
  5786. .fontColor($r('app.color.text_color'))
  5787. .margin({ left: 22 })
  5788. TextInput({ text: item.ALBUMARTIST })
  5789. .height(40)
  5790. .maxLines(1)
  5791. .fontSize(14)
  5792. .layoutWeight(1)
  5793. .fontColor($r('app.color.text_color'))
  5794. .margin({ right: 20, left: 10 })
  5795. .onChange((val: string) => {
  5796. this.albumArtistStr = val
  5797. })
  5798. }
  5799. .width('100%')
  5800. .margin({ top: 10, bottom: 10 })
  5801. .justifyContent(FlexAlign.Start)
  5802. Row() {
  5803. Text('作曲:')
  5804. .fontSize(14)
  5805. .fontColor($r('app.color.text_color'))
  5806. .margin({ left: 22 })
  5807. TextInput({ text: item.COMPOSER })
  5808. .height(40)
  5809. .maxLines(1)
  5810. .fontSize(14)
  5811. .layoutWeight(1)
  5812. .fontColor($r('app.color.text_color'))
  5813. .margin({ right: 20, left: 10 })
  5814. .onChange((val: string) => {
  5815. this.composerStr = val
  5816. })
  5817. }
  5818. .width('100%')
  5819. .margin({ top: 10, bottom: 10 })
  5820. .justifyContent(FlexAlign.Start)
  5821. Row() {
  5822. Text('作词:')
  5823. .fontSize(14)
  5824. .fontColor($r('app.color.text_color'))
  5825. .margin({ left: 22 })
  5826. TextInput({ text: item.LYRICIST })
  5827. .height(40)
  5828. .maxLines(1)
  5829. .fontSize(14)
  5830. .layoutWeight(1)
  5831. .fontColor($r('app.color.text_color'))
  5832. .margin({ right: 20, left: 10 })
  5833. .onChange((val: string) => {
  5834. this.lyricistStr = val
  5835. })
  5836. }
  5837. .width('100%')
  5838. .margin({ top: 10, bottom: 10 })
  5839. .justifyContent(FlexAlign.Start)
  5840. Row() {
  5841. Text('注释:')
  5842. .fontSize(14)
  5843. .fontColor($r('app.color.text_color'))
  5844. .margin({ left: 22 })
  5845. TextInput({ text: item.COMMENT })
  5846. .height(40)
  5847. .maxLines(1)
  5848. .fontSize(14)
  5849. .layoutWeight(1)
  5850. .fontColor($r('app.color.text_color'))
  5851. .margin({ right: 20, left: 10 })
  5852. .onChange((val: string) => {
  5853. this.commentStr = val
  5854. })
  5855. }
  5856. .width('100%')
  5857. .margin({ top: 10, bottom: 10 })
  5858. .justifyContent(FlexAlign.Start)
  5859. Row() {
  5860. Button('保存')
  5861. .fontColor(Color.White)
  5862. .layoutWeight(1)
  5863. .height(50)
  5864. .width(100)
  5865. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5866. .backgroundColor(this.themeColor)
  5867. .stateEffect(true)
  5868. .margin({ right: 20, bottom: 20 })
  5869. .onClick(async () => {
  5870. this.doEdit(item)
  5871. })
  5872. Button('取消')
  5873. .fontColor(Color.White)
  5874. .layoutWeight(1)
  5875. .height(50)
  5876. .width(100)
  5877. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5878. .backgroundColor(this.themeColor)
  5879. .stateEffect(true)
  5880. .margin({ left: 20, bottom: 20 })
  5881. .onClick(async () => {
  5882. if(this.isGridMusic){
  5883. this.longItemFilePath =''
  5884. }else{
  5885. this.isShowEdit = false
  5886. }
  5887. this.setEditStrEmpty()
  5888. if(this.isShowPlay){
  5889. this.isShowEdit = false
  5890. }
  5891. })
  5892. }
  5893. .margin({
  5894. left: 38,
  5895. right: 38,
  5896. top: 10,
  5897. bottom: 10
  5898. })
  5899. .width(250)
  5900. .height(60)
  5901. }
  5902. }
  5903. .margin({ bottom: 20 })
  5904. }
  5905. setEditStrEmpty(){
  5906. this.imagePathStr = ''
  5907. this.lyricConStr = ''
  5908. this.artistStr = ''
  5909. this.titleStr = ''
  5910. this.ablumStr = ''
  5911. this.genreStr = ''
  5912. this.yearStr = ''
  5913. this.trackStr = ''
  5914. this.albumArtistStr = ''
  5915. this.composerStr = ''
  5916. this.lyricistStr = ''
  5917. this.commentStr = ''
  5918. this.discStr = ''
  5919. }
  5920. @Builder
  5921. detailSheet(item:VideoItem) {
  5922. Scroll() {
  5923. Column() {
  5924. this.songDetail(item)
  5925. }
  5926. }
  5927. .width('100%')
  5928. .height('100%')
  5929. }
  5930. @Builder
  5931. songDetail(currentItem:VideoItem) {
  5932. Column() {
  5933. if (currentItem) {
  5934. Row() {
  5935. Stack() {
  5936. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  5937. currentItem.pixelMapPath)
  5938. .fillColor(this.themeColor)
  5939. .height(80)
  5940. .width(80)
  5941. .borderRadius(10)
  5942. .opacity(this.opacityItem)// 绑定透明度
  5943. .margin({ left: 22 })
  5944. }
  5945. Column() {
  5946. Column() {
  5947. Text(currentItem.name)
  5948. .fontSize(16)
  5949. .maxLines(1)
  5950. .animation({
  5951. duration: 555,
  5952. curve: 'Linear',
  5953. })
  5954. .fontColor($r('app.color.text_color'))
  5955. .margin({ left: 15 })
  5956. }
  5957. .height('100%')
  5958. .width('100%')
  5959. .justifyContent(FlexAlign.Center)
  5960. .alignItems(HorizontalAlign.Start)
  5961. }
  5962. .height('100%')
  5963. }
  5964. .width('100%')
  5965. .height(90)
  5966. .justifyContent(FlexAlign.SpaceBetween)
  5967. Row() {
  5968. Text('艺术家:')
  5969. .fontSize(14)
  5970. .fontColor($r('app.color.text_color'))
  5971. .margin({ left: 22 })
  5972. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  5973. .fontSize(14)
  5974. .fontColor($r('app.color.text_color'))
  5975. .margin({ left: 10 })
  5976. .layoutWeight(1)
  5977. }
  5978. .width('100%')
  5979. .margin({ top: 10, bottom: 10 })
  5980. .justifyContent(FlexAlign.Start)
  5981. Row() {
  5982. Text('专辑名:')
  5983. .fontSize(14)
  5984. .fontColor($r('app.color.text_color'))
  5985. .margin({ left: 22 })
  5986. Text(currentItem?.album ?currentItem.album : '未知专辑')
  5987. .fontSize(14)
  5988. .margin({ left: 10 })
  5989. .fontColor($r('app.color.text_color'))
  5990. .layoutWeight(1)
  5991. }
  5992. .width('100%')
  5993. .margin({ top: 10, bottom: 10 })
  5994. .justifyContent(FlexAlign.Start)
  5995. Row() {
  5996. Text('时长:')
  5997. .fontSize(14)
  5998. .fontColor($r('app.color.text_color'))
  5999. .margin({ left: 22 })
  6000. Text(StrUtil.isEmpty(currentItem.duration)?
  6001. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  6002. .fontSize(14)
  6003. .margin({ left: 10 })
  6004. .fontColor($r('app.color.text_color'))
  6005. .layoutWeight(1)
  6006. }
  6007. .width('100%')
  6008. .margin({ top: 10, bottom: 10 })
  6009. .justifyContent(FlexAlign.Start)
  6010. Row() {
  6011. Text('采样率:')
  6012. .fontSize(14)
  6013. .fontColor($r('app.color.text_color'))
  6014. .margin({ left: 22 })
  6015. Text(Utility.convertToKHz(currentItem.sampleRate))
  6016. .fontSize(14)
  6017. .margin({ left: 10 })
  6018. .fontColor($r('app.color.text_color'))
  6019. .layoutWeight(1)
  6020. }
  6021. .width('100%')
  6022. .margin({ top: 10, bottom: 10 })
  6023. .justifyContent(FlexAlign.Start)
  6024. Row() {
  6025. Text('比特率:')
  6026. .fontSize(14)
  6027. .fontColor($r('app.color.text_color'))
  6028. .margin({ left: 22 })
  6029. Text(currentItem.bit_rate)
  6030. .fontSize(14)
  6031. .margin({ left: 10 })
  6032. .fontColor($r('app.color.text_color'))
  6033. .layoutWeight(1)
  6034. }
  6035. .width('100%')
  6036. .margin({ top: 10, bottom: 10 })
  6037. .justifyContent(FlexAlign.Start)
  6038. Row() {
  6039. Text('位深:')
  6040. .fontSize(14)
  6041. .fontColor($r('app.color.text_color'))
  6042. .margin({ left: 22 })
  6043. Text(`${currentItem.bits_per_raw_sample} bits`)
  6044. .fontSize(14)
  6045. .margin({ left: 10 })
  6046. .fontColor($r('app.color.text_color'))
  6047. .layoutWeight(1)
  6048. }
  6049. .width('100%')
  6050. .margin({ top: 10, bottom: 10 })
  6051. .justifyContent(FlexAlign.Start)
  6052. Row() {
  6053. Text('声道:')
  6054. .fontSize(14)
  6055. .fontColor($r('app.color.text_color'))
  6056. .margin({ left: 22 })
  6057. Text(`${currentItem.channels}`)
  6058. .fontSize(14)
  6059. .margin({ left: 10 })
  6060. .fontColor($r('app.color.text_color'))
  6061. .layoutWeight(1)
  6062. }
  6063. .width('100%')
  6064. .margin({ top: 10, bottom: 10 })
  6065. .justifyContent(FlexAlign.Start)
  6066. Row() {
  6067. Text('声道布局:')
  6068. .fontSize(14)
  6069. .fontColor($r('app.color.text_color'))
  6070. .margin({ left: 22 })
  6071. Text(`${currentItem.channel_layout}`)
  6072. .fontSize(14)
  6073. .margin({ left: 10 })
  6074. .fontColor($r('app.color.text_color'))
  6075. .layoutWeight(1)
  6076. }
  6077. .width('100%')
  6078. .margin({ top: 10, bottom: 10 })
  6079. .justifyContent(FlexAlign.Start)
  6080. Row() {
  6081. Text('起始播放点:')
  6082. .fontSize(14)
  6083. .fontColor($r('app.color.text_color'))
  6084. .margin({ left: 22 })
  6085. Text(`${currentItem.start_time}`)
  6086. .fontSize(14)
  6087. .margin({ left: 10 })
  6088. .fontColor($r('app.color.text_color'))
  6089. .layoutWeight(1)
  6090. }
  6091. .width('100%')
  6092. .margin({ top: 10, bottom: 10 })
  6093. .justifyContent(FlexAlign.Start)
  6094. Row() {
  6095. Text('风格:')
  6096. .fontSize(14)
  6097. .fontColor($r('app.color.text_color'))
  6098. .margin({ left: 22 })
  6099. Text(currentItem.genre)
  6100. .fontSize(14)
  6101. .margin({ left: 10 })
  6102. .fontColor($r('app.color.text_color'))
  6103. .layoutWeight(1)
  6104. }
  6105. .width('100%')
  6106. .margin({ top: 10, bottom: 10 })
  6107. .justifyContent(FlexAlign.Start)
  6108. Row() {
  6109. Text('发行时间:')
  6110. .fontSize(14)
  6111. .fontColor($r('app.color.text_color'))
  6112. .margin({ left: 22 })
  6113. Text(currentItem.year)
  6114. .fontSize(14)
  6115. .margin({ left: 10 })
  6116. .fontColor($r('app.color.text_color'))
  6117. .layoutWeight(1)
  6118. }
  6119. .width('100%')
  6120. .margin({ top: 10, bottom: 10 })
  6121. .justifyContent(FlexAlign.Start)
  6122. Row() {
  6123. Text('质量评分:')
  6124. .fontSize(14)
  6125. .fontColor($r('app.color.text_color'))
  6126. .margin({ left: 22 })
  6127. Text(currentItem.probe_score+"")
  6128. .fontSize(14)
  6129. .margin({ left: 10 })
  6130. .fontColor($r('app.color.text_color'))
  6131. .layoutWeight(1)
  6132. }
  6133. .width('100%')
  6134. .margin({ top: 10, bottom: 10 })
  6135. .justifyContent(FlexAlign.Start)
  6136. Row() {
  6137. Text('音轨号:')
  6138. .fontSize(14)
  6139. .fontColor($r('app.color.text_color'))
  6140. .margin({ left: 22 })
  6141. Text(currentItem.track)
  6142. .fontSize(14)
  6143. .margin({ left: 10 })
  6144. .fontColor($r('app.color.text_color'))
  6145. .layoutWeight(1)
  6146. }
  6147. .width('100%')
  6148. .margin({ top: 10, bottom: 10 })
  6149. .justifyContent(FlexAlign.Start)
  6150. Row() {
  6151. Text('碟号:')
  6152. .fontSize(14)
  6153. .fontColor($r('app.color.text_color'))
  6154. .margin({ left: 22 })
  6155. Text(currentItem.disc)
  6156. .fontSize(14)
  6157. .margin({ left: 10 })
  6158. .fontColor($r('app.color.text_color'))
  6159. .layoutWeight(1)
  6160. }
  6161. .width('100%')
  6162. .margin({ top: 10, bottom: 10 })
  6163. .justifyContent(FlexAlign.Start)
  6164. Row() {
  6165. Text('专辑艺术家:')
  6166. .fontSize(14)
  6167. .fontColor($r('app.color.text_color'))
  6168. .margin({ left: 22 })
  6169. Text(currentItem.ALBUMARTIST)
  6170. .fontSize(14)
  6171. .margin({ left: 10 })
  6172. .fontColor($r('app.color.text_color'))
  6173. .layoutWeight(1)
  6174. }
  6175. .width('100%')
  6176. .margin({ top: 10, bottom: 10 })
  6177. .justifyContent(FlexAlign.Start)
  6178. Row() {
  6179. Text('作曲家:')
  6180. .fontSize(14)
  6181. .fontColor($r('app.color.text_color'))
  6182. .margin({ left: 22 })
  6183. Text(currentItem.COMPOSER)
  6184. .fontSize(14)
  6185. .margin({ left: 10 })
  6186. .fontColor($r('app.color.text_color'))
  6187. .layoutWeight(1)
  6188. }
  6189. .width('100%')
  6190. .margin({ top: 10, bottom: 10 })
  6191. .justifyContent(FlexAlign.Start)
  6192. Row() {
  6193. Text('作词家:')
  6194. .fontSize(14)
  6195. .fontColor($r('app.color.text_color'))
  6196. .margin({ left: 22 })
  6197. Text(currentItem.LYRICIST)
  6198. .fontSize(14)
  6199. .margin({ left: 10 })
  6200. .fontColor($r('app.color.text_color'))
  6201. .layoutWeight(1)
  6202. }
  6203. .width('100%')
  6204. .margin({ top: 10, bottom: 10 })
  6205. .justifyContent(FlexAlign.Start)
  6206. Row() {
  6207. Text('注释:')
  6208. .fontSize(14)
  6209. .fontColor($r('app.color.text_color'))
  6210. .margin({ left: 22 })
  6211. Text(currentItem.COMMENT)
  6212. .fontSize(14)
  6213. .margin({ left: 10 })
  6214. .fontColor($r('app.color.text_color'))
  6215. .layoutWeight(1)
  6216. }
  6217. .width('100%')
  6218. .margin({ top: 10, bottom: 10 })
  6219. .justifyContent(FlexAlign.Start)
  6220. Row() {
  6221. Text('格式:')
  6222. .fontSize(14)
  6223. .fontColor($r('app.color.text_color'))
  6224. .margin({ left: 22 })
  6225. Text(Utility.formatMimeType(currentItem.mimeType))
  6226. .fontSize(14)
  6227. .margin({ left: 10 })
  6228. .fontColor($r('app.color.text_color'))
  6229. .layoutWeight(1)
  6230. }
  6231. .width('100%')
  6232. .margin({ top: 10, bottom: 10 })
  6233. .justifyContent(FlexAlign.Start)
  6234. Row() {
  6235. Text('播放次数:')
  6236. .fontSize(14)
  6237. .fontColor($r('app.color.text_color'))
  6238. .margin({ left: 22 })
  6239. Text(currentItem.playCount?.toString())
  6240. .fontSize(14)
  6241. .margin({ left: 10 })
  6242. .fontColor($r('app.color.text_color'))
  6243. .layoutWeight(1)
  6244. }
  6245. .width('100%')
  6246. .margin({ top: 10, bottom: 10 })
  6247. .justifyContent(FlexAlign.Start)
  6248. Row() {
  6249. Text('流数量:')
  6250. .fontSize(14)
  6251. .fontColor($r('app.color.text_color'))
  6252. .margin({ left: 22 })
  6253. Text(currentItem.nb_streams?.toString())
  6254. .fontSize(14)
  6255. .margin({ left: 10 })
  6256. .fontColor($r('app.color.text_color'))
  6257. .layoutWeight(1)
  6258. }
  6259. .width('100%')
  6260. .margin({ top: 10, bottom: 10 })
  6261. .justifyContent(FlexAlign.Start)
  6262. Row() {
  6263. Text('文件大小:')
  6264. .fontSize(14)
  6265. .fontColor($r('app.color.text_color'))
  6266. .margin({ left: 22 })
  6267. Text(currentItem.size)
  6268. .fontSize(14)
  6269. .margin({ left: 10 })
  6270. .fontColor($r('app.color.text_color'))
  6271. .layoutWeight(1)
  6272. }
  6273. .width('100%')
  6274. .margin({ top: 10, bottom: 10 })
  6275. .justifyContent(FlexAlign.Start)
  6276. Row() {
  6277. Text('文件名:')
  6278. .fontSize(14)
  6279. .fontColor($r('app.color.text_color'))
  6280. .margin({ left: 22 })
  6281. Text(currentItem.fileName)
  6282. .fontSize(14)
  6283. .margin({ left: 10 })
  6284. .fontColor($r('app.color.text_color'))
  6285. .layoutWeight(1)
  6286. }
  6287. .width('100%')
  6288. .margin({ top: 10, bottom: 10 })
  6289. .justifyContent(FlexAlign.Start)
  6290. Row() {
  6291. Text('修改时间:')
  6292. .fontSize(14)
  6293. .fontColor($r('app.color.text_color'))
  6294. .margin({ left: 22 })
  6295. Text(currentItem.cTime)
  6296. .fontSize(14)
  6297. .margin({ left: 10 })
  6298. .fontColor($r('app.color.text_color'))
  6299. .layoutWeight(1)
  6300. }
  6301. .width('100%')
  6302. .margin({ top: 10, bottom: 10 })
  6303. .justifyContent(FlexAlign.Start)
  6304. Row() {
  6305. Text('存放目录:')
  6306. .fontSize(14)
  6307. .fontColor($r('app.color.text_color'))
  6308. .margin({ left: 22 })
  6309. Text(currentItem.filePath)
  6310. .fontSize(12)
  6311. .margin({ left: 10 })
  6312. .fontColor($r('app.color.text_color'))
  6313. .layoutWeight(1)
  6314. }
  6315. .margin({ top: 10, bottom: 10 })
  6316. .width('100%')
  6317. .justifyContent(FlexAlign.Start)
  6318. Row() {
  6319. Text('内嵌歌词:')
  6320. .fontSize(14)
  6321. .fontColor($r('app.color.text_color'))
  6322. .margin({ left: 22 })
  6323. Text(currentItem.lyricContent)
  6324. .fontSize(12)
  6325. .copyOption(CopyOptions.InApp)
  6326. .margin({ left: 10 })
  6327. .fontColor($r('app.color.text_color'))
  6328. .layoutWeight(1)
  6329. }
  6330. .margin({ top: 10, bottom: 10 })
  6331. .width('100%')
  6332. .justifyContent(FlexAlign.Start)
  6333. }
  6334. }
  6335. .margin({ bottom: 20 })
  6336. }
  6337. //定时关闭布局
  6338. @Builder
  6339. TimeCloseSheet() {
  6340. Scroll() {
  6341. Column() {
  6342. this.TimeClose()
  6343. }
  6344. }
  6345. .width('100%')
  6346. .height('100%')
  6347. }
  6348. //倒计时关闭音乐,退出App功能实现。
  6349. @State selectedMinutes: number = 0 // 0表示未开启
  6350. @State remainingSeconds: number = 0
  6351. // 预设时间选项
  6352. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  6353. private formatTime(seconds: number): string {
  6354. const mins = Math.floor(seconds / 60)
  6355. const secs = seconds % 60
  6356. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  6357. }
  6358. // 开始倒计时
  6359. private handleTimeSelect(minutes: number) {
  6360. if (minutes === this.selectedMinutes) {
  6361. this.stopCountdown();
  6362. this.selectedMinutes = 0;
  6363. return;
  6364. }
  6365. this.selectedMinutes = minutes;
  6366. this.remainingSeconds = minutes * 60;
  6367. this.startCountdown(); // 新增调用
  6368. }
  6369. @Builder
  6370. TimeClose() {
  6371. Column() {
  6372. // 倒计时显示区域
  6373. Text(this.selectedMinutes > 0 ?
  6374. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  6375. "定时关闭未开启")
  6376. .fontSize(17)
  6377. .fontColor($r('app.color.text_color'))
  6378. .margin({ top: 2, bottom: 8 });
  6379. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6380. ForEach(this.presetTimes, (minutes: number, index: number) => {
  6381. // 单行时间选项容器
  6382. Row() {
  6383. // 文字描述区域
  6384. Text(this.getDisplayText(minutes))
  6385. .fontSize(15)
  6386. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  6387. $r('app.color.text_color'))// 选中态颜色变化
  6388. .textAlign(TextAlign.Start)
  6389. .layoutWeight(1); // 占据剩余空间
  6390. // 复选框样式的选择器
  6391. Row() {
  6392. if (minutes === this.selectedMinutes) {
  6393. // 选中状态 - 带勾号的圆形复选框
  6394. Row() {
  6395. // 使用系统内置的勾号图标
  6396. Image($r('sys.media.ohos_ic_public_ok'))
  6397. .width(14)
  6398. .height(14)
  6399. .fillColor(Color.White)
  6400. }
  6401. .width(24)
  6402. .height(24)
  6403. .borderRadius(12)
  6404. .backgroundColor(this.themeColor)
  6405. .justifyContent(FlexAlign.Center)
  6406. .alignItems(VerticalAlign.Center)
  6407. } else {
  6408. // 未选中状态的圆形边框
  6409. Row()
  6410. .width(24)
  6411. .height(24)
  6412. .borderRadius(12)
  6413. .border({
  6414. width: 2,
  6415. color: $r('app.color.text_color'),
  6416. style: BorderStyle.Solid
  6417. })
  6418. .backgroundColor(Color.Transparent)
  6419. }
  6420. }
  6421. .width(24)
  6422. .height(24)
  6423. .margin({ left: 20 })
  6424. .justifyContent(FlexAlign.Center)
  6425. .alignItems(VerticalAlign.Center)
  6426. }
  6427. .width('100%')
  6428. .padding({
  6429. top: 18,
  6430. bottom: 18,
  6431. left: 18,
  6432. right: 18
  6433. })
  6434. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  6435. $r('app.color.bottom_control_background')) // 选中背景高亮
  6436. .borderRadius(12)
  6437. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6438. .margin({ bottom: 18 })
  6439. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  6440. });
  6441. }
  6442. .width('100%')
  6443. .padding(16)
  6444. }
  6445. }
  6446. // 获取显示文本
  6447. private getDisplayText(minutes: number): string {
  6448. if (minutes === -1) {
  6449. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  6450. }
  6451. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  6452. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  6453. }
  6454. // 处理选择事件
  6455. private handleSelect(minutes: number): void {
  6456. if (minutes === -1) { // 自定义
  6457. // 弹出自定义时间对话框
  6458. DialogHelper.showTextInputDialog({
  6459. title: '自定义时间',
  6460. maskColor: Color.Transparent,
  6461. inputType: InputType.Number,
  6462. text: '',
  6463. onChange: (text) => {
  6464. console.error("onChange: " + text);
  6465. },
  6466. onAction: (action, dialogId, content) => {
  6467. if (action == DialogAction.TWO) {
  6468. const customMinutes = Number(content);
  6469. if (customMinutes > 0) {
  6470. this.handleTimeSelect(customMinutes); // 设置自定义时间
  6471. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  6472. }
  6473. }
  6474. }
  6475. });
  6476. } else {
  6477. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  6478. }
  6479. }
  6480. // 添加定时器引用
  6481. private timerId: number = -1;
  6482. // 启动/重置倒计时
  6483. private startCountdown() {
  6484. // 清除旧定时器
  6485. if (this.timerId !== -1) {
  6486. clearInterval(this.timerId);
  6487. }
  6488. // 创建新定时器
  6489. if (this.selectedMinutes > 0) {
  6490. this.timerId = setInterval(() => {
  6491. if (this.remainingSeconds === 15) {
  6492. this.showConfirmationDialog();
  6493. }
  6494. if (this.remainingSeconds > 0) {
  6495. this.remainingSeconds -= 1;
  6496. } else {
  6497. this.stopCountdown();
  6498. this.handleTimeout();
  6499. }
  6500. }, 1000);
  6501. }
  6502. }
  6503. // 15倒计时后再次提示显示确认是否关闭App对话框
  6504. private showConfirmationDialog() {
  6505. DialogHelper.showAlertDialog({
  6506. backgroundColor: $r('app.color.btn_green'),
  6507. title: '确认关闭',
  6508. maskColor: Color.Transparent,
  6509. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  6510. borderStyle: BorderStyle.Dashed,
  6511. primaryButton: '暂不关闭',
  6512. secondaryButton: '确定',
  6513. onAction: (action) => {
  6514. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  6515. this.stopCountdown();
  6516. this.selectedMinutes = 0
  6517. } else if (action == DialogAction.TWO) {
  6518. }
  6519. }
  6520. })
  6521. }
  6522. // 停止倒计时
  6523. private stopCountdown() {
  6524. if (this.timerId !== -1) {
  6525. clearInterval(this.timerId);
  6526. this.timerId = -1;
  6527. }
  6528. }
  6529. // 超时处理
  6530. private handleTimeout() {
  6531. // 执行播放器关闭逻辑
  6532. this.selectedMinutes = 0;
  6533. ToastUtil.showToast(" 定时关闭已完成");
  6534. this.stop(); // 假设存在的播放器实例
  6535. //退出APP
  6536. const mContext = getContext(this) as common.UIAbilityContext
  6537. mContext.terminateSelf();
  6538. AvSessionController.getInstance(true).unregisterSessionListener()
  6539. }
  6540. //倒计时关闭音乐,退出App功能实现结束。
  6541. //播放列表的拖动List 重新排序
  6542. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  6543. //左滑操作 移动文件 重命名 删除等操作
  6544. @Builder
  6545. sonButton(item: VideoItem, index: number, filePath: string) {
  6546. Row() {
  6547. //加入下一首播放
  6548. Button() {
  6549. Image($r('app.media.next_to_play'))
  6550. .fillColor(Color.White)
  6551. .width(20)
  6552. }
  6553. .width(40)
  6554. .height(40)
  6555. .type(ButtonType.Circle)
  6556. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6557. .backgroundColor(this.themeColor)
  6558. .margin(5)
  6559. .onClick(() => {
  6560. this.addToNextPlay(item);
  6561. })
  6562. Button() {
  6563. Image($r('app.media.close'))
  6564. .fillColor(Color.White)
  6565. .width(20)
  6566. }
  6567. .width(40)
  6568. .height(40)
  6569. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6570. .type(ButtonType.Circle)
  6571. .backgroundColor(this.themeColor)
  6572. .margin(5)
  6573. .onClick(() => {
  6574. this.songList.splice(Number(index), 1)
  6575. this.sonDataSource.pushArrayData(this.songList)
  6576. })
  6577. Button() {
  6578. Image($r('app.media.share2'))
  6579. .fillColor(Color.White)
  6580. .width(20)
  6581. }
  6582. .width(40)
  6583. .height(40)
  6584. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6585. .type(ButtonType.Circle)
  6586. .backgroundColor(this.themeColor)
  6587. .margin(5)
  6588. .onClick(() => {
  6589. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6590. })
  6591. }
  6592. }
  6593. itemMoveSon(index: number, newIndex: number): void {
  6594. if (newIndex < 0 || newIndex >= this.songList.length) {
  6595. return;
  6596. }
  6597. let tmp = this.songList.splice(index, 1);
  6598. this.songList.splice(newIndex, 0, tmp[0]);
  6599. this.sonDataSource.pushArrayData(this.songList)
  6600. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  6601. }
  6602. @Builder
  6603. PlayList() {
  6604. List({ scroller: this.playListScroller }) {
  6605. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  6606. ListItem() {
  6607. this.MusicItemSon(item, index)
  6608. }
  6609. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  6610. .animation({
  6611. duration: 666,
  6612. curve: 'ease-in-out' // 可选动画曲线
  6613. })
  6614. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  6615. TransitionEffect.scale({ x: 0, y: 0 })))
  6616. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6617. //拖动List关键代码开始
  6618. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  6619. .zIndex(this.dragItem === index ? 1 : 0)
  6620. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  6621. .gesture(
  6622. GestureGroup(GestureMode.Sequence,
  6623. LongPressGesture({ repeat: true })
  6624. .onAction((event?: GestureEvent) => {
  6625. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6626. this.scaleItem = index
  6627. })
  6628. })
  6629. .onActionEnd(() => {
  6630. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6631. this.scaleItem = -1
  6632. })
  6633. }),
  6634. PanGesture({ fingers: 1, direction: null, distance: 0 })
  6635. .onActionStart(() => {
  6636. this.dragItem = index // 记录当前拖动项索引
  6637. this.dragRefOffset = 0 // 重置偏移基准
  6638. })
  6639. .onActionUpdate((event: GestureEvent) => {
  6640. this.offsetY = event.offsetY - this.dragRefOffset;
  6641. this.neighborItem = -1;
  6642. let indexA = this.songList.indexOf(item);
  6643. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6644. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6645. let value: number = 0;
  6646. if (this.offsetY < 0) {
  6647. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6648. this.neighborItem = indexA - 1;
  6649. this.neighborScale = 1 - value / 20;
  6650. } else if (this.offsetY > 0) {
  6651. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6652. this.neighborItem = indexA + 1;
  6653. this.neighborScale = 1 - value / 20;
  6654. }
  6655. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  6656. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6657. this.offsetY -= this.ITEM_INTV;
  6658. this.dragRefOffset += this.ITEM_INTV;
  6659. this.itemMoveSon(indexA, indexA + 1);
  6660. });
  6661. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6662. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6663. this.offsetY += this.ITEM_INTV;
  6664. this.dragRefOffset -= this.ITEM_INTV;
  6665. this.itemMoveSon(indexA, indexA - 1);
  6666. });
  6667. }
  6668. })
  6669. .onActionEnd((event: GestureEvent) => {
  6670. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6671. this.dragItem = -1
  6672. this.neighborItem = -1
  6673. })
  6674. animateTo({
  6675. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6676. }, () => {
  6677. this.scaleItem = -1
  6678. })
  6679. })
  6680. )
  6681. .onCancel(() => {
  6682. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6683. this.dragItem = -1
  6684. this.neighborItem = -1
  6685. })
  6686. animateTo({
  6687. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6688. }, () => {
  6689. this.scaleItem = -1
  6690. })
  6691. })
  6692. ) //拖动List关键代码结束
  6693. .onClick(() => {
  6694. this.doPlay(item, index, true)
  6695. })
  6696. }, (item: VideoItem) => item.filePath)
  6697. }
  6698. .width('100%')
  6699. .height('100%')
  6700. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  6701. // .animation({ duration: 500, curve: Curve.Ease }))
  6702. .cachedCount(10)
  6703. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6704. .gesture(PinchGesture({ fingers: 2 })
  6705. .onActionEnd((event: GestureEvent) => {
  6706. this.setSonListTwoFingers()
  6707. })
  6708. .onActionUpdate(e => {
  6709. this.scaleValue = this.pinchValue * e.scale
  6710. })
  6711. .onActionStart(e => {
  6712. }))
  6713. .padding({
  6714. bottom: 0
  6715. })
  6716. }
  6717. setSonListTwoFingers() {
  6718. this.pinchValue = this.scaleValue;
  6719. Logger.info('this.pinchValue = ' + this.pinchValue);
  6720. if (this.pinchValue >= 1) {
  6721. this.sonTwoFingerType++
  6722. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  6723. if (this.sonTwoFingerType > 3) {
  6724. this.sonTwoFingerType = 1
  6725. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6726. }
  6727. } else {
  6728. this.sonTwoFingerType--
  6729. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  6730. if (this.sonTwoFingerType < 1) {
  6731. this.sonTwoFingerType = 1
  6732. }
  6733. }
  6734. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  6735. this.pinchValue = 1;
  6736. this.scaleValue = 1;
  6737. }
  6738. @State sonTwoFingerType:number = 3
  6739. @Builder
  6740. private MusicItemSon(item: VideoItem, index?: number) {
  6741. Button({ type: ButtonType.Normal, stateEffect: true }) {
  6742. Row() {
  6743. Stack() {
  6744. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  6745. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6746. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6747. .alt($r('app.media.music_red'))
  6748. .fillColor(this.themeColor)
  6749. .borderRadius('100%')
  6750. .clip(true)
  6751. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  6752. .draggable(false)// 禁止长按手势拖动
  6753. .autoResize(true) // 重采样,可减少内存占用
  6754. .margin({ left: 20 })
  6755. }
  6756. .width('15%')
  6757. Column() {
  6758. Column() {
  6759. Text(this.isShowFileName?item.fileName :item.name)
  6760. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  6761. .fontColor(this.curIndex === index ? this.themeColor :
  6762. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  6763. .maxLines(1)
  6764. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  6765. Row() {
  6766. Column(){
  6767. Text(item.md5Str?.includes('Lossless')?
  6768. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6769. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  6770. .padding({ top: 3,right:6,left:6,bottom:3 })
  6771. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6772. $r('app.color.text_color'))
  6773. .fontWeight(500)
  6774. .borderRadius(12)
  6775. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  6776. .backgroundColor('#FFC107')
  6777. }
  6778. .padding({ top: 8 })
  6779. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  6780. item.artist + ' ' + item?.duration)
  6781. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6782. .padding({ top: 8 })
  6783. .maxLines(1)
  6784. .fontColor(this.curIndex === index ? this.themeColor :
  6785. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6786. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  6787. Blank()
  6788. Text(item.size)
  6789. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6790. .padding({ top: 8 })
  6791. .maxLines(1)
  6792. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  6793. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  6794. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6795. .margin({ left: 10 })
  6796. }
  6797. }
  6798. .height('100%')
  6799. .width('100%')
  6800. .justifyContent(FlexAlign.Center)
  6801. .alignItems(HorizontalAlign.Start)
  6802. }
  6803. .height('100%')
  6804. .width('65%')
  6805. Column() {
  6806. ImageAnimator()
  6807. .images(this.imagesF)// 动画数组
  6808. .duration(1000)// 持续
  6809. .state(this.animationState)// 动画状态
  6810. .fillMode(FillMode.Forwards)
  6811. .width(18)
  6812. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  6813. Visibility.None)
  6814. .height(18)
  6815. .iterations(-1) // 播放次数
  6816. }
  6817. .width('20%')
  6818. }
  6819. }
  6820. .backgroundColor(Color.Transparent)
  6821. .width('100%')
  6822. .reuseId('son_item')
  6823. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  6824. .shadow(this.scaleItem === index ? {
  6825. radius: 70,
  6826. color: '#15000000',
  6827. offsetX: 0,
  6828. offsetY: 0
  6829. } :
  6830. {
  6831. radius: 0,
  6832. color: '#15000000',
  6833. offsetX: 0,
  6834. offsetY: 0
  6835. })
  6836. .animation({ curve: Curve.Sharp, duration: 300 })
  6837. }
  6838. @Builder
  6839. MusicPlayBuilder() {
  6840. Column() {
  6841. this.IjkMusicPlayerView()
  6842. }
  6843. .height('100%')
  6844. .width('100%')
  6845. .onDisAppear(() => {
  6846. this.translateY = 0;
  6847. })
  6848. .translate({ y: this.translateY })
  6849. .gesture(
  6850. PanGesture(this.panOption)
  6851. .onActionUpdate((event?: GestureEvent) => {
  6852. if (event) {
  6853. // 只允许向下滑动,向上滑动时限制为0
  6854. this.translateY = Math.max(0, event.offsetY);
  6855. }
  6856. })
  6857. .onActionEnd((event?: GestureEvent) => {
  6858. // 使用更低的阈值和滑动速度判断
  6859. const minDistance = 100; // 最小滑动距离 100vp
  6860. const minVelocity = 500; // 最小滑动速度
  6861. // 获取滑动速度(如果可用)
  6862. const velocity = event?.velocityY || 0;
  6863. // 判断是否应该关闭:距离足够 或者 速度足够快
  6864. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  6865. if (shouldClose) {
  6866. // 添加关闭动画
  6867. this.getUIContext().animateTo({
  6868. duration: 300,
  6869. curve: Curve.Smooth
  6870. }, () => {
  6871. this.isShowPlay = false;
  6872. this.translateY = 0;
  6873. })
  6874. } else {
  6875. // 回弹动画
  6876. this.getUIContext().animateTo({
  6877. duration: 300,
  6878. curve: Curve.Smooth
  6879. }, () => {
  6880. this.translateY = 0;
  6881. })
  6882. }
  6883. })
  6884. )
  6885. }
  6886. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  6887. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  6888. HeightBreakpoint.HEIGHT_LG;
  6889. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  6890. @State topBarHeight: number = 50
  6891. @State barOpacity: number = 1
  6892. @State barBottomOpacity: number = 1
  6893. private hideDone: boolean = false;
  6894. @State currentYOffset: number = 0;
  6895. @State bottomBarHeight: number = 55;
  6896. private isHiding: boolean = false;
  6897. //是否是Pura X外屏,或者小屏幕
  6898. isPuraWP() {
  6899. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6900. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  6901. }
  6902. //是否是Pura X外屏,或者小屏幕,手机横屏
  6903. /**
  6904. * 是否是Pura X外屏,或者小屏幕,手机横屏
  6905. * @returns
  6906. */
  6907. isCoverOpacity() {
  6908. if (this.isPuraWP()) {
  6909. return true
  6910. }
  6911. if (this.isPhoneLan()) {
  6912. return true
  6913. }
  6914. if (deviceInfo.marketName.includes('Pura X')
  6915. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  6916. return true
  6917. }
  6918. return false
  6919. }
  6920. //是不是手机横屏
  6921. isPhoneLan() {
  6922. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  6923. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  6924. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  6925. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  6926. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  6927. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  6928. if (this.isHiCarKuanBianPing()) {
  6929. return true
  6930. }
  6931. if (this.isHiCar()) {
  6932. return false
  6933. }
  6934. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6935. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  6936. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  6937. return true
  6938. }
  6939. return false
  6940. }
  6941. //是不是1920x720的hicar的屏幕分辨率
  6942. isHiCarKuanBianPing(){
  6943. if(!this.isHiCar()){
  6944. return false
  6945. }
  6946. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6947. { ratio: 1920 / 720, name: "1920x720" },
  6948. ];
  6949. const currentRatio: number = this.windowWidth / this.windowHeight;
  6950. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6951. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  6952. for (const hiCarRatio of hiCarAspectRatios) {
  6953. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  6954. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6955. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6956. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6957. //宽扁平的尺寸设置列表展示
  6958. this.twoFingerType ==3
  6959. this.isGridMusic = false
  6960. return true;
  6961. }
  6962. }
  6963. return false;
  6964. }
  6965. //是不是hicar的屏幕分辨率
  6966. isHiCarSmall() {
  6967. if(!this.isHiCar()){
  6968. return false
  6969. }
  6970. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  6971. {
  6972. this.columns = 6
  6973. return false
  6974. }
  6975. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6976. { ratio: 800 / 480, name: "800x480" },
  6977. { ratio: 1280 / 720, name: "1280x720" },
  6978. { ratio: 1920 / 1080, name: "1920x1080" },
  6979. ];
  6980. const currentRatio: number = this.windowWidth / this.windowHeight;
  6981. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6982. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  6983. for (const hiCarRatio of hiCarAspectRatios) {
  6984. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  6985. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6986. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  6987. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6988. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6989. //宽扁平的尺寸设置列表展示
  6990. return true;
  6991. }
  6992. }
  6993. return false;
  6994. }
  6995. isHiCar() {
  6996. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  6997. }
  6998. //是不是正常的手机竖屏
  6999. isPhonePortrait() {
  7000. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  7001. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  7002. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  7003. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7004. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  7005. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  7006. return true
  7007. }
  7008. return false
  7009. }
  7010. @State showSpeedDialog: boolean = false
  7011. @State longPressSpeed: number = 3 //长按默认倍数
  7012. @Builder
  7013. SpeedDialog() {
  7014. Stack() {
  7015. Column() {
  7016. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7017. .fontColor(Color.White)
  7018. .visibility(Visibility.Hidden)
  7019. }
  7020. .backgroundColor(Color.Black)
  7021. .borderRadius(20)
  7022. .padding({
  7023. top: 10,
  7024. right: 20,
  7025. left: 15,
  7026. bottom: 20
  7027. })
  7028. .opacity(0.6)
  7029. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7030. .fontColor(Color.White)
  7031. }
  7032. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  7033. .zIndex(5)
  7034. .margin({ top: 80 })
  7035. }
  7036. @Builder
  7037. IjkMusicPlayerView() {
  7038. Column() {
  7039. Column() {
  7040. Column() {
  7041. //播放标题
  7042. Column() {
  7043. this.PlayTitle()
  7044. }
  7045. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  7046. .width('100%')
  7047. .margin({ top: 0 })
  7048. .height(PlayConstants.HEIGHT)
  7049. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  7050. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  7051. if (this.showSpeedDialog) {
  7052. this.SpeedDialog()
  7053. }
  7054. Stack() {
  7055. //手势拖动快进
  7056. Column()
  7057. .width(CommonConstants.FULL_PERCENT)
  7058. .height('100%')
  7059. .gesture(
  7060. GestureGroup(GestureMode.Parallel,
  7061. // 长按屏幕倍数播放
  7062. LongPressGesture({ repeat: true })
  7063. .onAction(() => {
  7064. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7065. this.showSpeedDialog = true;
  7066. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  7067. }
  7068. })
  7069. .onActionEnd(() => {
  7070. this.showSpeedDialog = false;
  7071. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7072. }),
  7073. //双击屏幕暂停或者播放
  7074. TapGesture({ count: 2 })
  7075. .onAction((event: GestureEvent) => {
  7076. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7077. ToastUtil.showToast('已暂停')
  7078. }
  7079. console.info('onecold playOrPause 6693')
  7080. this.playOrPause()
  7081. })
  7082. )
  7083. )
  7084. }
  7085. .height('65%')
  7086. Swiper() {
  7087. this.CoverInfo()
  7088. this.PlayerLyrics()
  7089. }
  7090. .onChange((index: number) => {
  7091. this.currentSwiperIndex = index
  7092. })
  7093. .indicator(false)
  7094. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  7095. // new DotIndicator()
  7096. // .top(this.isCoverOpacity()?0:10)
  7097. //
  7098. // .selectedColor($r('app.color.select_swiper'))
  7099. // .color($r('app.color.slider_track')):false
  7100. // )
  7101. .displayCount(new BreakpointType({
  7102. sm: 1,
  7103. md: 2,
  7104. lg: 2,
  7105. xl: 2,
  7106. xxl: 2
  7107. }).getValue(this.currentBreakpoint))
  7108. .clip(false)
  7109. .loop(false)
  7110. .autoPlay(false)
  7111. // .interval(8000)
  7112. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  7113. .height('100%')
  7114. .hitTestBehavior(HitTestMode.Transparent)
  7115. Image($r('app.media.icon_replay'))
  7116. .objectFit(ImageFit.Auto)
  7117. .width('120px')
  7118. .height('120px')
  7119. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  7120. .border({ width: 0 })
  7121. .visibility(Visibility.None)
  7122. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  7123. .onClick(() => {
  7124. console.info('onecold startPlayOrResumePlay 6744')
  7125. this.startPlayOrResumePlay();
  7126. })
  7127. }
  7128. .width(CommonConstants.FULL_PERCENT)
  7129. .height(CommonConstants.FULL_PERCENT)
  7130. .justifyContent(FlexAlign.End)
  7131. }
  7132. .justifyContent(FlexAlign.End)
  7133. .margin({ bottom: 8 })
  7134. }
  7135. .backgroundImage(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7136. // .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  7137. // (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  7138. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  7139. // .backgroundImagePosition(Alignment.Center)
  7140. .animation({
  7141. duration: 666,
  7142. curve: 'ease-in-out' // 可选动画曲线
  7143. })
  7144. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  7145. BlurStyle.BACKGROUND_ULTRA_THICK)
  7146. .hitTestBehavior(HitTestMode.Transparent)
  7147. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  7148. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  7149. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  7150. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  7151. .onClick(() => {
  7152. // this.startAutoHide()
  7153. if(this.isHiCar())
  7154. return
  7155. if(this.is_auto_hide_progress){
  7156. this.is_auto_hide_progress = false
  7157. }
  7158. this.startAutoHide()
  7159. })
  7160. }
  7161. @State progressValue: number = 0;
  7162. @State currentTime: string = "00:00";
  7163. @State totalTime: string = "00:00";
  7164. @State loadingVisible: Visibility = Visibility.None;
  7165. @State replayVisible: Visibility = Visibility.None;
  7166. @State slideEnable: boolean = false;
  7167. @State aspRatio: number = 0.5;
  7168. @State mContext: object | undefined = undefined;
  7169. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  7170. @State mFirst: boolean = true;
  7171. @State mDestroyPage: boolean = false;
  7172. @State playSpeed: number = 1;
  7173. @State oldSeconds: number = 0;
  7174. @State isSeekTo: boolean = false;
  7175. @State isCurrentTime: boolean = false;
  7176. @State videoWidth: string = '100%';
  7177. @State videoHeight: string = '100%';
  7178. @State initAspectRatio: number = 1;
  7179. @State videoAspectRatio: number = this.initAspectRatio;
  7180. private videoUrl: string = '';
  7181. private last: number = 0;
  7182. @State videoParentAspectRatio: number = this.initAspectRatio;
  7183. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  7184. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  7185. @State PROGRESS_MAX_VALUE: number = 100;
  7186. @State updateProgressTimer: number = 0;
  7187. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  7188. @State name: string = '';
  7189. // @State loop: boolean = false;
  7190. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  7191. @State multiple: string = '1.0X';
  7192. xcomponentController: XComponentController = new XComponentController()
  7193. private panOptionBright: PanGestureOptions =
  7194. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  7195. private panOptionVolume: PanGestureOptions =
  7196. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  7197. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  7198. //手势的音量控制和亮度控制
  7199. private positionX: number = PlayConstants.POSITION_X;
  7200. private positionY: number = PlayConstants.POSITION_Y;
  7201. private windowClass: window.Window = globalThis.windowClass
  7202. @State volume: number = 0.5;
  7203. @State volumeSmall: boolean = false
  7204. @State autoParseMusicName: boolean = true
  7205. @State isShowFileName: boolean = false
  7206. @State isLongNameRoLL: boolean = true//长歌名滚动
  7207. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  7208. @State bright: number = PlayConstants.BRIGHT;
  7209. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  7210. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  7211. @State screenWidth: number = 0
  7212. @State screenHeight: number = 0
  7213. @State statusBarHeight: number = 0
  7214. @State isYesFull: boolean = false
  7215. private seekValue: number = 0
  7216. @State isVideoLock: boolean = false; // Whether the video playback is locked
  7217. eventHub = getContext().eventHub;
  7218. //投播组件
  7219. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  7220. private castController: avSession.AVCastController | undefined = undefined;
  7221. @State isCastPlaying: boolean = false;
  7222. @State currentTime2: number = 0;
  7223. @State currentStringTime: string = '00:00';
  7224. @State duration: number = 0;
  7225. @State isReady: boolean = false;
  7226. @State durationTime: number = 0;
  7227. @State durationStringTime: string = '00:00';
  7228. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  7229. // @State isPlaying: boolean = false;
  7230. private castSeek: boolean = false;
  7231. private castItem: avSession.AVQueueItem | undefined = undefined;
  7232. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  7233. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  7234. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  7235. @State rotateAngle2: number = -9
  7236. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  7237. @State cover: string | undefined = '';
  7238. @State artist: string | undefined = ''
  7239. // 1.初始化controller
  7240. private lyricController: LyricController = new LyricController()
  7241. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  7242. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  7243. private parser = new LyricParser()
  7244. @State randomColor: string = 'rgb(0,0,0)'
  7245. @State randomShakenX: number = 0
  7246. @State randomShakenY: number = 0
  7247. @State lyricTextSize: number = 24
  7248. @State lyricContent: string = ''
  7249. @State isDebug: boolean = false
  7250. @State isHightLightCenter: boolean = true
  7251. /**
  7252. * 初始化歌词加载与展示逻辑
  7253. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  7254. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  7255. * @param isApi2 是否使用API2获取歌词(可选)
  7256. *
  7257. * 主要流程:
  7258. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  7259. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  7260. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  7261. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  7262. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  7263. * 6. 解析失败或读取失败时,清空歌词显示。
  7264. *
  7265. * 注意事项:
  7266. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  7267. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  7268. * - 歌词内容解析后通过lyricController驱动UI渲染。
  7269. */
  7270. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  7271. if (StrUtil.isEmpty(lyricPath)) {
  7272. return
  7273. }
  7274. this.initPipLyricSetting()
  7275. this.lyricControllerSingle
  7276. .setTextSize(15)
  7277. .setCacheSize(4)
  7278. .setTextColor("#FFFFFF")
  7279. .setHighlightColor("#FFFFFF")
  7280. .setHighlightScale(1.2)
  7281. .setEmptyHint("")
  7282. .setAlignMode('center')
  7283. .setAnimationDuration(500)
  7284. .setSingleLine(true)
  7285. this.lyricContent = ''
  7286. this.lyricController
  7287. .setTextSize(this.currentLyricSize)
  7288. .setCacheSize(4)
  7289. .setTextColor("#DDDDDD")
  7290. .setHighlightColor("#FFFFFF")
  7291. .setEmptyHint("")
  7292. .setAnimationDuration(1000)
  7293. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  7294. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  7295. this.setBlurDegree(this.blurDegree, false)
  7296. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  7297. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  7298. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  7299. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  7300. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  7301. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  7302. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  7303. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7304. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  7305. this.lyricController.setTextWeight(this.lyricTextWeight)
  7306. this.showSingleLyric = false
  7307. this.timeOffset = 0
  7308. this.lyricController.setLyric(null)
  7309. this.lyricControllerSingle.setLyric(null)
  7310. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  7311. console.log("onecold lyricPath =" + lyricPath)
  7312. let neiqianLrc = ''
  7313. let lyContent = this.currentSong?.lyricContent
  7314. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  7315. neiqianLrc = lyContent
  7316. }
  7317. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  7318. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  7319. //赋值给this.lyricContent,播控中心才可以显示歌词
  7320. this.lyricContent = neiqianLrc
  7321. // 将文件内容按行分割成字符串数组
  7322. let lines = neiqianLrc.split('\n').map(line => line.trim());
  7323. // 3.解析歌词
  7324. let lyric = this.parser.parse(lines);
  7325. // 4.设置歌词
  7326. this.lyricController.setLyric(lyric);
  7327. this.lyricControllerXF.setLyric(lyric)
  7328. this.lyricControllerSingle.setLyric(lyric)
  7329. return
  7330. }
  7331. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  7332. && !Utility.isVideoByExtension(this.videoUrl))) {
  7333. if (this.currentSong !== undefined) {
  7334. // ToastUtil.showShort('正在为你搜索在线歌词!')
  7335. //判断是不是赞助会员,是会员的话才开启歌词功能
  7336. // if (!this.isDebug) {
  7337. // if (!Utility.isNoble()) {
  7338. // LogUtil.debug("onecold 不是赞助会员")
  7339. // return
  7340. // }
  7341. // if(!Utility.isPassInstallTime(33)){
  7342. // LogUtil.debug("onecold not pass time")
  7343. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  7344. // return
  7345. // }
  7346. // }
  7347. let artist = this.currentSong?.artist
  7348. if (artist === undefined) {
  7349. artist = ''
  7350. }
  7351. if (isApi2 === undefined) {
  7352. isApi2 = false
  7353. }
  7354. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  7355. // LogUtil.debug("onecold res =" + res)
  7356. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7357. if (StrUtil.isNotEmpty(res)) {
  7358. this.lyricContent = res
  7359. let lines = res.split('\n').map(line => line.trim());
  7360. // 3.解析歌词
  7361. let lyric = this.parser.parse(lines);
  7362. // 4.设置歌词
  7363. this.lyricController.setLyric(lyric);
  7364. this.lyricControllerXF.setLyric(lyric)
  7365. this.lyricControllerSingle.setLyric(lyric)
  7366. this.showSingleLyric = true
  7367. // 4.保存歌词文件lyric到本地
  7368. //2025年8月28日歌词不再加密下载
  7369. this.saveDataToFile(res, lyricPath, false)
  7370. } else {
  7371. this.lyricController.setLyric(null)
  7372. this.lyricControllerXF.setLyric(null)
  7373. this.lyricControllerSingle.setLyric(null)
  7374. if (isOnLineAndToast) {
  7375. ToastUtil.showShort('未获取到歌词!')
  7376. }
  7377. }
  7378. } else {
  7379. this.lyricController.setLyric(null)
  7380. this.lyricControllerXF.setLyric(null)
  7381. this.lyricControllerSingle.setLyric(null)
  7382. if (isOnLineAndToast) {
  7383. ToastUtil.showShort('未获取到歌词!')
  7384. }
  7385. }
  7386. })
  7387. } else {
  7388. this.lyricController.setLyric(null)
  7389. this.lyricControllerXF.setLyric(null)
  7390. this.lyricControllerSingle.setLyric(null)
  7391. if (isOnLineAndToast) {
  7392. ToastUtil.showShort('未获取到歌词!')
  7393. }
  7394. }
  7395. return
  7396. }
  7397. try {
  7398. let isJiaMi = false;
  7399. let realLyricPath = lyricPath
  7400. if (FileUtil.accessSync(jiaMilyricPath)) {
  7401. isJiaMi = true
  7402. realLyricPath = jiaMilyricPath
  7403. console.info("onecold 找到加密本地歌词 ");
  7404. } else {
  7405. isJiaMi = false
  7406. realLyricPath = lyricPath
  7407. console.info("onecold 找到本地歌词 ");
  7408. }
  7409. // 3.读取文件内容并指定编码为 UTF-8
  7410. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7411. const stat = await fileIo.stat(file.fd);
  7412. const arrayBuffer = new ArrayBuffer(stat.size);
  7413. fs.read(file.fd, arrayBuffer)
  7414. .then((readLen: number) => {
  7415. console.info("read file data succeed");
  7416. // let buf = buffer.from(arrayBuffer, 0, readLen);
  7417. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7418. // 检查 buf 是否为空
  7419. if (buf.length === 0) {
  7420. throw new Error("Buffer is empty after reading the file");
  7421. }
  7422. try {
  7423. // 检测文件编码
  7424. // let detectedEncoding = chardet.detect(buf);
  7425. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  7426. let detectedEncoding = this.detect(arrayBuffer)
  7427. console.info("onecoldT Detected encoding: " + detectedEncoding);
  7428. // 使用检测到的编码解码,解决中文乱码问题
  7429. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7430. console.info("onecoldT Detected textDecoder: " + textDecoder);
  7431. let fileContent = textDecoder.decode(buf);
  7432. console.info(`onecoldT The content of file1: ${fileContent}`);
  7433. //解密
  7434. if (isJiaMi) {
  7435. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  7436. }
  7437. console.info(`onecold The content of file2: ${fileContent}`);
  7438. this.lyricContent = fileContent
  7439. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  7440. this.lyricConStr = fileContent
  7441. }
  7442. // 将文件内容按行分割成字符串数组
  7443. let lines = fileContent.split('\n').map(line => line.trim());
  7444. console.info(`onecold The content of file: ${fileContent}`);
  7445. // 3.解析歌词
  7446. let lyric = this.parser.parse(lines);
  7447. // 4.设置歌词
  7448. this.lyricController.setLyric(lyric);
  7449. this.lyricControllerXF.setLyric(lyric)
  7450. this.lyricControllerSingle.setLyric(lyric)
  7451. this.showSingleLyric = true
  7452. console.info(`The content of file: ${fileContent}`);
  7453. } catch (chardetError) {
  7454. console.error("chardet.detect failed with error: " + chardetError.message);
  7455. this.lyricController.setLyric(null);
  7456. this.lyricControllerXF.setLyric(null)
  7457. this.lyricControllerSingle.setLyric(null)
  7458. }
  7459. })
  7460. .catch((err: BusinessError) => {
  7461. this.lyricController.setLyric(null)
  7462. this.lyricControllerXF.setLyric(null)
  7463. this.lyricControllerSingle.setLyric(null)
  7464. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  7465. })
  7466. .catch((err: Error) => {
  7467. this.lyricController.setLyric(null)
  7468. this.lyricControllerXF.setLyric(null)
  7469. this.lyricControllerSingle.setLyric(null)
  7470. console.error("read file 2 data failed with error message: " + err.message);
  7471. })
  7472. .finally(() => {
  7473. fs.closeSync(file);
  7474. });
  7475. } catch (error) {
  7476. this.lyricController.setLyric(null)
  7477. this.lyricControllerSingle.setLyric(null)
  7478. this.lyricControllerXF.setLyric(null)
  7479. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  7480. }
  7481. }
  7482. detect(data: ArrayBuffer): string {
  7483. //创建检测对象
  7484. let detector: UniversalDetector = new UniversalDetector();
  7485. // 传入检测数据并实时判断编码格式
  7486. detector.handleData(data, 0, data.byteLength);
  7487. // 标记检测数据 读取结束
  7488. detector.dataEnd();
  7489. // 获取检测结果
  7490. let detected: string = detector.getDetectedCharset();
  7491. // 释放资源
  7492. detector.reset();
  7493. return detected;
  7494. }
  7495. //初始化悬浮歌词的自定义设置
  7496. initPipLyricSetting() {
  7497. this.lyricControllerXF
  7498. .setTextSize(this.currentLyricSize)
  7499. .setCacheSize(4)
  7500. .setTextColor("#DDDDDD")
  7501. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  7502. .setEmptyHint("")
  7503. .setAnimationDuration(1000)
  7504. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  7505. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  7506. this.setBlurDegree(this.blurDegreePip, true)
  7507. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  7508. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  7509. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  7510. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  7511. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  7512. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  7513. this.lyricControllerXF.setHightLightCenter(true)
  7514. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  7515. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7516. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7517. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  7518. if (this.pipBgIndex === 0) {
  7519. if (this.cover) {
  7520. this.pipBg = this.cover
  7521. } else {
  7522. this.pipBg = this.imageColor
  7523. }
  7524. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7525. }
  7526. }
  7527. //根据item返回歌词内容
  7528. async getLyricContent(item: VideoItem): Promise<string> {
  7529. let neiqianLrc = ''
  7530. let lyContent = item?.lyricContent
  7531. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  7532. neiqianLrc = lyContent
  7533. return neiqianLrc
  7534. }
  7535. try {
  7536. //取数据库里面的歌词lyContent
  7537. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  7538. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  7539. console.log("onecold Lyrics:", lyricContent);
  7540. neiqianLrc = lyricContent
  7541. return neiqianLrc
  7542. }
  7543. } catch (error) {
  7544. console.error("Error fetching lyrics:", error);
  7545. }
  7546. try {
  7547. let filePath = item.filePath;
  7548. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  7549. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  7550. let isJiaMi = false;
  7551. let realLyricPath = lyricPath;
  7552. if (FileUtil.accessSync(jiaMilyricPath)) {
  7553. isJiaMi = true;
  7554. realLyricPath = jiaMilyricPath;
  7555. console.info("onecold 找到加密本地歌词");
  7556. } else {
  7557. console.info("onecold 找到本地歌词");
  7558. }
  7559. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7560. const stat = await fileIo.stat(file.fd);
  7561. const arrayBuffer = new ArrayBuffer(stat.size);
  7562. const readLen = await fs.read(file.fd, arrayBuffer);
  7563. console.info("read file data succeed");
  7564. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7565. if (buf.length === 0) {
  7566. throw new Error("Buffer is empty after reading the file");
  7567. }
  7568. // let detectedEncoding = chardet.detect(buf);
  7569. let detectedEncoding = this.detect(arrayBuffer)
  7570. console.info("Detected encoding: " + detectedEncoding);
  7571. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7572. let fileContent = textDecoder.decode(buf);
  7573. console.info(`onecold The content of file1: ${fileContent}`);
  7574. if (isJiaMi) {
  7575. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  7576. }
  7577. console.info(`onecold The content of file2: ${fileContent}`);
  7578. fs.closeSync(file);
  7579. return fileContent;
  7580. } catch (error) {
  7581. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  7582. return '';
  7583. }
  7584. }
  7585. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  7586. if (StrUtil.isEmpty(filePath)) {
  7587. return
  7588. }
  7589. try {
  7590. //将content进行加密
  7591. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  7592. let lyricContent = ''
  7593. if (isJiaMi) {
  7594. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  7595. } else {
  7596. lyricContent = content
  7597. }
  7598. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  7599. // 清空文件内容
  7600. await fileIo.truncate(file.fd, 0);
  7601. await fileIo.write(file.fd, lyricContent);
  7602. await fileIo.close(file);
  7603. console.log('onecold lyric file Data saved successfully.');
  7604. } catch (error) {
  7605. console.error('onecold lyric file Failed to save data:', error);
  7606. }
  7607. }
  7608. /**
  7609. * Get largest proportion color of an image.
  7610. */
  7611. getImageColor() {
  7612. if (!this.context) {
  7613. return;
  7614. }
  7615. let bg = Utility.getMusisBg()
  7616. this.imageLabel = bg
  7617. ColorConversion.setSysBarLightBackground(true);
  7618. this.context.resourceManager.getMediaContent(bg)
  7619. .then((value: Uint8Array) => {
  7620. let buffer = value.buffer as ArrayBuffer;
  7621. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  7622. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  7623. if (error) {
  7624. Logger.error('Failed to create color picker.');
  7625. } else {
  7626. let color = colorPicker.getLargestProportionColor();
  7627. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  7628. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  7629. }
  7630. })
  7631. let headFilter = effectKit.createEffect(pixelMap);
  7632. if (headFilter !== null) {
  7633. headFilter.blur(15);
  7634. headFilter.getEffectPixelMap().then((value) => {
  7635. this.imageLabelBg = value;
  7636. })
  7637. }
  7638. })
  7639. .catch((error: BusinessError) => {
  7640. Logger.error(`${error.code} + ${error.message}`)
  7641. })
  7642. })
  7643. .catch((error: BusinessError) => {
  7644. Logger.error(`${error.code} + ${error.message}`)
  7645. })
  7646. }
  7647. setImageColor(cover: string) {
  7648. if (!this.context) {
  7649. return;
  7650. }
  7651. if (cover === undefined) {
  7652. return;
  7653. }
  7654. imagePathToPixelMap(cover).then((value) => {
  7655. let headFilter = effectKit.createEffect(value);
  7656. if (headFilter !== null) {
  7657. headFilter.blur(15);
  7658. headFilter.getEffectPixelMap().then((value) => {
  7659. this.imageLabelBg = value;
  7660. })
  7661. }
  7662. }).catch((error: BusinessError) => {
  7663. Logger.error(`${error.code} + ${error.message}`)
  7664. })
  7665. }
  7666. setImageColor2(cover: string) {
  7667. if (!this.context) {
  7668. return;
  7669. }
  7670. if (cover === undefined) {
  7671. return;
  7672. }
  7673. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  7674. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  7675. this.imageColor = data.imageColor;
  7676. if (data.blurPixelMap) {
  7677. this.imageLabelBg = data.blurPixelMap;
  7678. }
  7679. })
  7680. }
  7681. // 定义开始旋转的方法
  7682. // 定时器用于一百毫秒执行一次旋转角度
  7683. @State timer: number = 0
  7684. @State rotateAngle: number = 0
  7685. //封面旋转动画
  7686. animationRoFun() {
  7687. if (this.isPlaying && !this.isCoverRectangle) {
  7688. this.timer = setInterval(() => {
  7689. this.rotateAngle += 1
  7690. }, 100)
  7691. this.startRotation()
  7692. } else {
  7693. clearInterval(this.timer)
  7694. this.stopRotation()
  7695. }
  7696. }
  7697. // 定义开始旋转的方法
  7698. startRotation() {
  7699. if (this.isPlaying) {
  7700. animateTo({
  7701. duration: 777,
  7702. iterations: 1,
  7703. curve: Curve.Linear
  7704. }, () => {
  7705. this.rotateAngle2 = -9
  7706. })
  7707. }
  7708. }
  7709. // 回调,暂停和播放按钮回调,下一首和上一首
  7710. playChange() {
  7711. // if(this.isCoverRectangle){
  7712. // return
  7713. // }
  7714. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7715. this.setIsPlaying(true)
  7716. this.animationState = AnimationStatus.Running
  7717. } else {
  7718. this.setIsPlaying(false)
  7719. this.animationState = AnimationStatus.Paused
  7720. }
  7721. }
  7722. // 定义停止旋转的方法
  7723. stopRotation() {
  7724. if (this.isCoverRectangle) {
  7725. this.rotateAngle = 0
  7726. } else {
  7727. //唱针以左上角为点选择逆时针40度
  7728. animateTo({
  7729. duration: 1000,
  7730. curve: Curve.Linear,
  7731. iterations: 1,
  7732. }, () => {
  7733. this.rotateAngle2 = -45;
  7734. });
  7735. }
  7736. }
  7737. @Builder
  7738. private LyricsTopItem() {
  7739. Row() {
  7740. Stack() {
  7741. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7742. .height(62)
  7743. .width(62)
  7744. .alt(this.imageLabel)
  7745. .borderRadius(8)
  7746. .clickEffect({ level: ClickEffectLevel.HEAVY })
  7747. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  7748. .shadow({
  7749. radius: 22,
  7750. type: ShadowType.BLUR,
  7751. color: 'on_primary'
  7752. })
  7753. }
  7754. .width('18%')
  7755. Column() {
  7756. Column() {
  7757. Text(this.name)
  7758. .fontSize(16)
  7759. .maxLines(1)
  7760. .fontWeight(FontWeight.Bolder)
  7761. .fontColor(this.currentLyricColor)
  7762. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7763. Row() {
  7764. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  7765. .fontSize(13)
  7766. .fontWeight(FontWeight.Bold)
  7767. .padding({ top: 8 })
  7768. .fontColor(this.currentLyricColor)
  7769. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7770. Blank()
  7771. }
  7772. }
  7773. .height('100%')
  7774. .width('100%')
  7775. .justifyContent(FlexAlign.Center)
  7776. .alignItems(HorizontalAlign.Start)
  7777. }
  7778. .height('100%')
  7779. .width('65%')
  7780. Column() {
  7781. Image($r('app.media.lyric'))
  7782. .width(28)
  7783. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7784. .margin({ right: 30 })
  7785. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7786. .onClick(() => {
  7787. this.isLyricSetting = !this.isLyricSetting;
  7788. })
  7789. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  7790. height: '95%',
  7791. dragBar: true,
  7792. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7793. showClose: true,
  7794. blurStyle: BlurStyle.Thin,
  7795. backgroundColor: Color.Transparent,
  7796. // title: { title: $r('app.string.lyric_setting') }
  7797. })
  7798. }
  7799. .width('18%')
  7800. }
  7801. .width('82%')
  7802. .height(58)
  7803. .justifyContent(FlexAlign.SpaceBetween)
  7804. }
  7805. //歌词显示
  7806. @Builder
  7807. PlayerLyrics() {
  7808. Column() {
  7809. Column() {
  7810. this.LyricsTopItem()
  7811. }
  7812. .height(this.isPuraWP() ? 15 : 58)
  7813. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  7814. Visibility.None : Visibility.Visible)
  7815. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  7816. .width("100%")
  7817. Column() {
  7818. LyricView2({
  7819. controller: this.lyricController,
  7820. enableSeek: true,
  7821. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7822. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7823. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7824. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  7825. if (!this.isPlaying) {
  7826. console.info('onecold startPlayOrResumePlay 7527')
  7827. this.startPlayOrResumePlay()
  7828. }
  7829. else {
  7830. this.isSeekTo = true;
  7831. this.mDestroyPage = false;
  7832. this.showLoadIng();
  7833. this.seekTo(position + "");
  7834. this.isSeekTo = false;
  7835. }
  7836. return true
  7837. }
  7838. })
  7839. .width("100%")
  7840. .layoutWeight(1)
  7841. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  7842. if (this.isPhoneLan()) {
  7843. Column() {
  7844. this.playProgressView()
  7845. // this.playCenterView()
  7846. }
  7847. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  7848. }
  7849. }
  7850. .position({
  7851. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  7852. (this.isPuraWP() ? 58 : 99)
  7853. })
  7854. .justifyContent(FlexAlign.Center)
  7855. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  7856. }
  7857. }
  7858. @Builder
  7859. SingleLyricView() {
  7860. Column() {
  7861. Column() {
  7862. LyricView2({
  7863. controller: this.lyricControllerSingle,
  7864. enableSeek: false,
  7865. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7866. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7867. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7868. })
  7869. }
  7870. .height(66)
  7871. .margin({ bottom: 20 })
  7872. }
  7873. }
  7874. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  7875. @Builder
  7876. BottomControl() {
  7877. Column() {
  7878. this.TopPlayProgressView()
  7879. //播放 暂停,下一首,上一首
  7880. this.playCenterView()
  7881. //播放进度条
  7882. this.BottomView()
  7883. }
  7884. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  7885. }
  7886. //播放控制上一首 下一首 暂停和播放
  7887. @Builder
  7888. playCenterView(){
  7889. Row() {
  7890. Row({ space: 20 }) {
  7891. Button({type:ButtonType.Circle,stateEffect:true}){
  7892. //更多功能
  7893. Image($r('app.media.menu'))
  7894. .width(24)
  7895. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7896. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  7897. height: this.isCoverOpacity() ? '95%' : '93%',
  7898. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  7899. dragBar: true,
  7900. showClose: true,
  7901. blurStyle: BlurStyle.Thin,
  7902. backgroundColor: Color.Transparent,
  7903. })
  7904. }
  7905. .margin({ left: 5 })
  7906. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7907. .backgroundColor(Color.Transparent)
  7908. .onClick(() => {
  7909. this.isShowMoreView = !this.isShowMoreView;
  7910. })
  7911. Button({type:ButtonType.Circle,stateEffect:true}){
  7912. Image($r('app.media.ic_previous'))
  7913. .width(33)
  7914. .clickEffect({level:ClickEffectLevel.HEAVY})
  7915. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7916. }
  7917. .onClick(async () => {
  7918. this.playPrevious()
  7919. })
  7920. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7921. .backgroundColor(Color.Transparent)
  7922. .margin({ left: 5 })
  7923. }
  7924. Button({type:ButtonType.Circle,stateEffect:true}){
  7925. Column() {
  7926. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  7927. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  7928. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  7929. .width(this.isPhoneLan()?45:55)
  7930. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7931. .fillColor(Color.White)
  7932. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7933. .onClick(async () => {
  7934. console.info('onecold playOrPause 7651')
  7935. this.playOrPause()
  7936. })
  7937. }
  7938. }
  7939. .backgroundColor(Color.Transparent)
  7940. .layoutWeight(1)
  7941. // .margin({ left: 38, right: 38 })
  7942. Row({ space: 20 }) {
  7943. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7944. Image($r('app.media.ic_next'))
  7945. .width(33)
  7946. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7947. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7948. .onClick(() => {
  7949. this.playNext();
  7950. })
  7951. }
  7952. .backgroundColor(Color.Transparent)
  7953. .margin({ right: 5 })
  7954. .width(33)
  7955. if(this.isPhoneLan()){
  7956. this.fullButton()
  7957. }else{
  7958. Button({type:ButtonType.Circle,stateEffect:true}){
  7959. //添加或取消收藏
  7960. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  7961. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  7962. .fontSize(23)
  7963. .fontColor([Color.White])
  7964. .alignSelf(ItemAlign.Center)
  7965. // .width(24)
  7966. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7967. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7968. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7969. .onClick(async () => {
  7970. if(this.currentSong){
  7971. this.doFav(this.currentSong)
  7972. }
  7973. })
  7974. }
  7975. .backgroundColor(Color.Transparent)
  7976. .width(24)
  7977. }
  7978. }
  7979. // .margin({ left: 5 })
  7980. }
  7981. .width('95%')
  7982. .margin({ bottom:this.isCoverOpacity()?0:20 })
  7983. .justifyContent(FlexAlign.SpaceEvenly)
  7984. }
  7985. @Builder
  7986. TopPlayProgressView(){
  7987. Row() {
  7988. Column(){
  7989. Row(){
  7990. Stack(){
  7991. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  7992. .fontColor([Color.White])
  7993. .fontSize(21)
  7994. .effectStrategy(1)
  7995. Text(this.fastForwardSeconds)
  7996. .fontColor(Color.White)
  7997. .fontSize(10)
  7998. .fontWeight(FontWeight.Bold)
  7999. }
  8000. .margin({left:12,bottom:6})
  8001. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8002. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8003. .onClick(()=>{
  8004. this.backForward()
  8005. })
  8006. Slider({
  8007. value: this.progressValue,
  8008. min: 0,
  8009. max: this.PROGRESS_MAX_VALUE,
  8010. step: 1,
  8011. style: SliderStyle.InSet
  8012. })
  8013. .height(20)
  8014. .blockColor('rgba(255,255,255,1)')
  8015. .trackColor('rgba(255,255,255,0.3)')
  8016. .selectedColor(Color.White)
  8017. .trackThickness(4)
  8018. .layoutWeight(1)
  8019. .showSteps(false)
  8020. .showTips(true)
  8021. .alignSelf(ItemAlign.Center)
  8022. .enabled(this.slideEnable)
  8023. .onChange((value: number, mode: SliderChangeMode) => {
  8024. // if (mode == 2) {
  8025. this.isSeekTo = true;
  8026. this.mDestroyPage = false;
  8027. this.showLoadIng();
  8028. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8029. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8030. this.seekTo(seekValue + "");
  8031. // this.setProgress()
  8032. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8033. this.isSeekTo = false;
  8034. // }
  8035. })
  8036. Stack(){
  8037. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  8038. .fontColor([Color.White])
  8039. .fontSize(21)
  8040. .effectStrategy(1)
  8041. Text(this.fastForwardSeconds)
  8042. .fontColor(Color.White)
  8043. .fontSize(10)
  8044. .fontWeight(FontWeight.Bold)
  8045. }
  8046. .margin({right:10,bottom:6})
  8047. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8048. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8049. .onClick(()=>{
  8050. this.fastForward()
  8051. })
  8052. }
  8053. .padding({ right: 7,left:22 })
  8054. Row(){
  8055. Text(this.currentTime)
  8056. .fontSize(10)
  8057. .fontColor(Color.White)
  8058. Blank()
  8059. .layoutWeight(1)
  8060. Text(this.totalTime)
  8061. .fontSize(10)
  8062. .fontColor(Color.White)
  8063. }
  8064. .justifyContent(FlexAlign.Start)
  8065. .padding({ right: 18,left:36 })
  8066. }
  8067. }
  8068. //x5的竖屏模式需要99%
  8069. .width(this.isLandscape?'80%':'93%')
  8070. .justifyContent(FlexAlign.Center)
  8071. .margin({bottom:6})
  8072. .animation({
  8073. duration: 666,
  8074. curve: 'ease-in-out' // 可选动画曲线
  8075. })
  8076. }
  8077. //播放进度条
  8078. @Builder
  8079. BottomView(){
  8080. Row() {
  8081. Button({type:ButtonType.Circle,stateEffect:true}){
  8082. Column() {
  8083. if (this.playType === 0) {
  8084. Image($r('app.media.loop'))
  8085. .width(27)
  8086. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8087. } else if (this.playType === 1) {
  8088. Image($r('app.media.single'))
  8089. .width(27)
  8090. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8091. } else if (this.playType === 2) {
  8092. Image($r('app.media.normal_play'))
  8093. .width(27)
  8094. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8095. } else if (this.playType === 3) {
  8096. Image($r('app.media.random'))
  8097. .width(27)
  8098. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8099. }
  8100. }
  8101. }
  8102. .layoutWeight(1)
  8103. .margin({ left: 5 })
  8104. .backgroundColor(Color.Transparent)
  8105. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8106. .onClick(async () => {
  8107. this.setLoopMode()
  8108. })
  8109. this.fullButton()
  8110. Button({type:ButtonType.Circle,stateEffect:true}){
  8111. Column() {
  8112. Image($r('app.media.lyric'))
  8113. .width(26)
  8114. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8115. }
  8116. }
  8117. .layoutWeight(1)
  8118. .backgroundColor(Color.Transparent)
  8119. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8120. .onClick(async () => {
  8121. this.isLyricSetting = !this.isLyricSetting;
  8122. })
  8123. //播放列表
  8124. Button({type:ButtonType.Circle,stateEffect:true}){
  8125. Image($r('app.media.hm_playlist'))
  8126. .width(24)
  8127. .fillColor(Color.White)
  8128. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8129. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8130. height: '95%',
  8131. dragBar: true,
  8132. showClose: true,
  8133. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8134. blurStyle: BlurStyle.Thin,
  8135. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  8136. title: {
  8137. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8138. + `(${this.songList.length}首)`
  8139. }
  8140. })
  8141. }
  8142. .layoutWeight(1)
  8143. .backgroundColor(Color.Transparent)
  8144. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8145. .onClick(() => {
  8146. this.isShowSheetView = !this.isShowSheetView;
  8147. if(this.isPlayListBgGrass){
  8148. this.isFrontWhite = true
  8149. }else{
  8150. this.isFrontWhite = false
  8151. }
  8152. this.scrollIndex()
  8153. })
  8154. }
  8155. .width(this.isLandscape?'88%':'95%')
  8156. .justifyContent(FlexAlign.SpaceAround)
  8157. .height(30)
  8158. .margin({top:3})
  8159. .animation({
  8160. duration: 666,
  8161. curve: 'ease-in-out' // 可选动画曲线
  8162. })
  8163. }
  8164. @Builder
  8165. fullButton(){
  8166. Button({type:ButtonType.Circle,stateEffect:true}){
  8167. Column() {
  8168. Image($r('app.media.full_4'))
  8169. .width(25)
  8170. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8171. }
  8172. }
  8173. .layoutWeight(1)
  8174. .backgroundColor(Color.Transparent)
  8175. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8176. .onClick(async () => {
  8177. if (this.isLandscape) {
  8178. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8179. } else {
  8180. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8181. }
  8182. })
  8183. }
  8184. //旧版本播放进度条
  8185. @Builder
  8186. playProgressView() {
  8187. Row() {
  8188. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8189. Column() {
  8190. if (this.playType === 0) {
  8191. Image($r('app.media.loop'))
  8192. .width($r('app.float.control_image_width'))
  8193. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8194. } else if (this.playType === 1) {
  8195. Image($r('app.media.single'))
  8196. .width($r('app.float.control_image_width'))
  8197. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8198. } else if (this.playType === 2) {
  8199. Image($r('app.media.normal_play'))
  8200. .width($r('app.float.control_image_width'))
  8201. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8202. } else if (this.playType === 3) {
  8203. Image($r('app.media.random'))
  8204. .width($r('app.float.control_image_width'))
  8205. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8206. }
  8207. }
  8208. }
  8209. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8210. .animation({
  8211. duration: 666,
  8212. curve: 'ease-in-out' // 可选动画曲线
  8213. })
  8214. .backgroundColor(Color.Transparent)
  8215. .margin({ right: 10 })
  8216. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8217. .onClick(async () => {
  8218. this.setLoopMode()
  8219. })
  8220. Text(this.currentTime)
  8221. .fontSize($r('app.float.slider_font_size'))
  8222. .fontColor(Color.White)
  8223. .margin(3)
  8224. Slider({
  8225. value: this.progressValue,
  8226. min: 0,
  8227. max: this.PROGRESS_MAX_VALUE,
  8228. step: 1,
  8229. style: SliderStyle.OutSet
  8230. })
  8231. .width('600px')
  8232. .blockColor('rgba(255,255,255,1)')
  8233. .trackColor('rgba(255,255,255,0.3)')
  8234. .selectedColor(Color.White)
  8235. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  8236. .layoutWeight(1)
  8237. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8238. .showSteps(false)
  8239. .showTips(true)
  8240. .enabled(this.slideEnable)
  8241. .onChange((value: number, mode: SliderChangeMode) => {
  8242. // if (mode == 2) {
  8243. this.isSeekTo = true;
  8244. this.mDestroyPage = false;
  8245. this.showLoadIng();
  8246. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8247. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8248. this.seekTo(seekValue + "");
  8249. // this.setProgress()
  8250. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8251. this.isSeekTo = false;
  8252. // }
  8253. })
  8254. Text(this.totalTime)
  8255. .fontSize($r('app.float.slider_font_size'))
  8256. .fontColor(Color.White)
  8257. .margin(3)
  8258. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8259. //播放列表
  8260. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8261. Image($r('app.media.hm_playlist'))
  8262. .width($r('app.float.control_image_width'))
  8263. .fillColor(Color.White)
  8264. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8265. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8266. height: '95%',
  8267. dragBar: true,
  8268. showClose: true,
  8269. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8270. blurStyle: BlurStyle.Thin,
  8271. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  8272. title: {
  8273. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8274. + `(${this.songList.length}首)`
  8275. }
  8276. })
  8277. }
  8278. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8279. .animation({
  8280. duration: 666,
  8281. curve: 'ease-in-out' // 可选动画曲线
  8282. })
  8283. .backgroundColor(Color.Transparent)
  8284. .margin({ right: 20, left: 10 })
  8285. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8286. .onClick(() => {
  8287. this.isShowSheetView = !this.isShowSheetView;
  8288. if (this.isPlayListBgGrass) {
  8289. this.isFrontWhite = true
  8290. } else {
  8291. this.isFrontWhite = false
  8292. }
  8293. this.scrollIndex()
  8294. })
  8295. }
  8296. //x5的竖屏模式需要99%
  8297. .width(this.isPhonePortrait() ? '93.4%'
  8298. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  8299. .height(this.isPhoneLan() ? 25 : 33)
  8300. .animation({
  8301. duration: 666,
  8302. curve: 'ease-in-out' // 可选动画曲线
  8303. })
  8304. }
  8305. isBigScreen() {
  8306. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  8307. return true
  8308. }
  8309. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8310. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8311. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  8312. return false
  8313. } else {
  8314. return true
  8315. }
  8316. return false
  8317. }
  8318. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  8319. @State isCoverRectangle: boolean = false
  8320. @State isCoverTop: boolean = true
  8321. // 添加控制缩放的状态变量
  8322. @State scaleValueImage: number = 1
  8323. @Builder
  8324. CoverInfo() {
  8325. Column() {
  8326. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  8327. if (this.isCoverRectangle) {
  8328. if (!this.isCoverTop) {
  8329. this.musicNameInfo(false)
  8330. }
  8331. } else {
  8332. this.musicNameInfo(false)
  8333. }
  8334. Stack() {
  8335. // 唱片旋转效果
  8336. Image($r('app.media.ic_music_disc'))
  8337. .width(245)
  8338. .height(245)
  8339. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  8340. .aspectRatio(1)
  8341. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8342. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8343. .borderRadius('100%')
  8344. .align(Alignment.Center)
  8345. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  8346. .rotate({
  8347. angle: this.rotateAngle,
  8348. centerX: "50%",
  8349. centerY: "50%",
  8350. })
  8351. .animation({
  8352. duration: 100,
  8353. curve: Curve.Linear
  8354. })
  8355. .shadow({
  8356. radius: 22,
  8357. type: ShadowType.BLUR,
  8358. color: 'on_primary'
  8359. })
  8360. Column() {
  8361. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  8362. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8363. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  8364. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  8365. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8366. .alt(this.imageLabel)
  8367. .margin({ right: 8, left: 8, top: 8 })
  8368. .aspectRatio(1)
  8369. .opacity(this.opacityValueImage)
  8370. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8371. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8372. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8373. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8374. .align(Alignment.Center)//
  8375. .clip(true)
  8376. .rotate({
  8377. x: 0,
  8378. y: 0,
  8379. z: 1,
  8380. angle: this.rotateAngle
  8381. })
  8382. .shadow({
  8383. radius: 22,
  8384. type: ShadowType.BLUR,
  8385. color: 'on_primary'
  8386. })
  8387. .onClick(() => {
  8388. this.getImageColor()
  8389. })
  8390. this.musicNameInfo(false)
  8391. } else {
  8392. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8393. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  8394. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  8395. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8396. .alt(this.imageLabel)
  8397. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  8398. .aspectRatio(1)
  8399. .opacity(this.opacityValueImage)
  8400. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8401. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8402. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8403. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8404. .align(Alignment.Center)//
  8405. .clip(true)
  8406. .shadow({
  8407. radius: 22,
  8408. type: ShadowType.BLUR,
  8409. color: 'on_primary'
  8410. })
  8411. .rotate({
  8412. x: 0,
  8413. y: 0,
  8414. z: 1,
  8415. angle: this.rotateAngle
  8416. })
  8417. .onClick(() => {
  8418. this.getImageColor()
  8419. })
  8420. if (this.isPhoneLan()) {
  8421. Text(this.name)
  8422. .fontSize(18)
  8423. .fontWeight(FontWeight.Bold)
  8424. .margin({ top: 13 })
  8425. .textOverflow({ overflow: TextOverflow.Ellipsis })
  8426. .maxLines(1)
  8427. .width('99%')
  8428. .textAlign(TextAlign.Center)
  8429. .fontColor(Color.White)
  8430. }
  8431. }
  8432. }
  8433. // 唱针以左上角为点选择逆时针40度
  8434. Image($r('app.media.ic_music_cover_hand'))
  8435. .height(130)
  8436. .margin({ bottom: 220, top: 0 })
  8437. .align(Alignment.Top)
  8438. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  8439. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8440. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8441. Column({ space: 8 }) {
  8442. Text(this.name)
  8443. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  8444. .fontWeight(FontWeight.Bold)
  8445. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8446. .maxLines(1)
  8447. .width('48%')
  8448. .textAlign(TextAlign.Center)
  8449. .fontColor(Color.White)
  8450. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8451. Text(this.artist)
  8452. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  8453. .fontColor(Color.White)
  8454. .fontWeight(FontWeight.Bold)
  8455. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8456. }
  8457. .justifyContent(FlexAlign.Start)
  8458. .zIndex(1)
  8459. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  8460. }
  8461. .margin({
  8462. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  8463. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  8464. top: this.isCoverOpacity() ? 0 : 20
  8465. })
  8466. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  8467. this.SingleLyricView()
  8468. }
  8469. if (this.isPhoneLan()) {
  8470. Column() {
  8471. this.playCenterView()
  8472. // this.playProgressView()
  8473. }
  8474. .position({ left: 28, bottom: 38 })
  8475. } else {
  8476. this.BottomControl()
  8477. }
  8478. }
  8479. .width(CommonConstants.FULL_PERCENT)
  8480. .clip(true)
  8481. }
  8482. @Builder
  8483. private musicNameInfo(isHidden: boolean) {
  8484. Column({ space: 8 }) {
  8485. Text(this.name)
  8486. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  8487. .fontWeight(FontWeight.Bold)
  8488. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8489. .maxLines(1)
  8490. .width('99%')
  8491. .textAlign(TextAlign.Center)
  8492. .fontColor(Color.White)
  8493. Text(this.artist + ' ' + this.currentSong?.album)
  8494. .fontSize(this.isCoverOpacity() ? 12 : 15)
  8495. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8496. .fontColor(Color.White)
  8497. .textAlign(TextAlign.Center)
  8498. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  8499. .width('99%')
  8500. .maxLines(1)
  8501. }
  8502. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  8503. .zIndex(1)
  8504. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8505. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  8506. }
  8507. @Builder
  8508. private PlayTitle() {
  8509. Row() {
  8510. Row() {
  8511. Image($r('app.media.ic_back_down'))
  8512. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  8513. .hitTestBehavior(HitTestMode.Transparent)
  8514. Text(this.name + ' ' + this.artist)
  8515. .fontColor(Color.White)
  8516. .fontSize($r('app.float.title_font_size'))
  8517. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8518. .maxLines(1)
  8519. .visibility(Visibility.None)
  8520. .margin({ left: 2, right: 30 })
  8521. }
  8522. .layoutWeight(1)
  8523. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8524. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  8525. .onClick(() => {
  8526. this.isShowPlay = false;
  8527. })
  8528. Column() {
  8529. AVCastPicker({
  8530. normalColor: Color.White,
  8531. onStateChange: this.onStateVastChange
  8532. })
  8533. .width(24)
  8534. .height(24)
  8535. }
  8536. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  8537. }
  8538. .width(PlayConstants.ROW_WIDTH)
  8539. }
  8540. @Builder
  8541. lyricSettingSheet(isPip: boolean) {
  8542. Scroll() {
  8543. this.lyricSetting(isPip)
  8544. }
  8545. .width('100%')
  8546. .height('100%')
  8547. }
  8548. @Builder
  8549. lyricSetting(isPip: boolean) {
  8550. Column() {
  8551. // 时间调节模块
  8552. if (!isPip) {
  8553. this.BuildTimeControls()
  8554. }
  8555. // 字号控制模块
  8556. this.BuildFontControls(isPip)
  8557. }
  8558. }
  8559. // 歌词时间偏移状态
  8560. @State timeOffset: number = 0.0
  8561. @State currentLyricColor: string = '#FFFFFF'
  8562. @State currentLyricColorPip: string = '#FFFFFF'
  8563. @State currentHighLightLyricColor: string = '#FF4081'
  8564. @State currentHighLightLyricColorPip: string = '#FF4081'
  8565. // 歌词字号状态
  8566. @State currentLyricSize: number = 20
  8567. @State currentLyricSizePip: number = 20
  8568. // 高亮歌词放大倍数
  8569. @State currentHightLyricSize: number = 1.2
  8570. @State currentHightLyricSizePip: number = 1.2
  8571. @State currentLyricLineSpace: number = 10
  8572. @State currentLyricLineSpacePip: number = 10
  8573. @State currentLyricAlignMode: number = 1
  8574. @State currentLyricAlignModePip: number = 1
  8575. @State blurDegree: number = 2
  8576. @State blurDegreePip: number = 2
  8577. @State isShowSelectColor: boolean = false
  8578. @State isShowHLSelectColor: boolean = false
  8579. @State isShowPipBgSelectColor: boolean = false
  8580. @State pipLyWidth: number = 330
  8581. @State pipLyHeight: number = 120
  8582. // 构建颜色选择器
  8583. @Builder
  8584. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  8585. Row({ space: 10 }) {
  8586. HSBColorPicker({
  8587. color: '#FFFFFF',
  8588. radius: 8,
  8589. layout: HSBColorPickerLayout.COLUMN,
  8590. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  8591. '#fa7105'],
  8592. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  8593. this.changeLyricColor(value, isPip, isBGPip)
  8594. })
  8595. .height(250)
  8596. .layoutWeight(1)
  8597. .padding(25)
  8598. }
  8599. .width('66%')
  8600. }
  8601. @State isOpenPip: boolean = false
  8602. @State pipBgIndex: number = 0
  8603. // 构建字号控制器
  8604. @Builder
  8605. BuildFontControls(isPip: boolean) {
  8606. Column() {
  8607. if (isPip) {
  8608. Column() {
  8609. Row() {
  8610. Text('悬浮歌词')
  8611. .margin({ left: 18 })
  8612. .fontSize(15)
  8613. .fontColor(Color.White)
  8614. .fontWeight(480)
  8615. .layoutWeight(1)
  8616. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  8617. .selectedColor(this.themeColor)
  8618. .switchPointColor(Color.White)
  8619. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8620. .margin({ right: 18 })
  8621. .onChange((checked: boolean) => {
  8622. this.isOpenPip = checked;
  8623. if (this.isOpenPip) {
  8624. this.startPip()
  8625. } else {
  8626. this.stopPip()
  8627. }
  8628. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  8629. })
  8630. .width(50)
  8631. .height(30);
  8632. }
  8633. .height(55)
  8634. }
  8635. .backgroundColor(Color.Transparent)
  8636. .borderRadius(15)
  8637. .margin({
  8638. left: 30,
  8639. right: 30,
  8640. top: 0,
  8641. bottom: 20
  8642. })
  8643. .padding(0)
  8644. .border({
  8645. color: Color.White,
  8646. width: 1.8
  8647. })
  8648. }else{
  8649. Column() {
  8650. Row() {
  8651. Text('单行歌词')
  8652. .margin({ left: 18 })
  8653. .fontSize(15)
  8654. .fontColor(Color.White)
  8655. .fontWeight(480)
  8656. .layoutWeight(1)
  8657. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  8658. .selectedColor(this.themeColor)
  8659. .switchPointColor(Color.White)
  8660. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8661. .margin({ right: 18 })
  8662. .onChange((checked: boolean) => {
  8663. this.isShowSingleLineLyric = checked;
  8664. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  8665. })
  8666. .width(50)
  8667. .height(30);
  8668. }
  8669. .height(55)
  8670. }
  8671. .backgroundColor(Color.Transparent)
  8672. .borderRadius(15)
  8673. .margin({
  8674. left: 30,
  8675. right: 30,
  8676. top: 10,
  8677. bottom: 10
  8678. })
  8679. .padding(0)
  8680. .border({
  8681. color: Color.White,
  8682. width: 1.8
  8683. })
  8684. }
  8685. Row() {
  8686. Text(`歌词居中:`)
  8687. .fontSize(14)
  8688. .fontColor(Color.White)
  8689. .margin({ left: 2 })
  8690. Row() {
  8691. ForEach(['居中', '居左'], (size: string, index: number) => {
  8692. Button(size)
  8693. .width(60)
  8694. .height(28)
  8695. .fontSize(12)
  8696. .fontColor('#FFFFFF')
  8697. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  8698. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  8699. .border({
  8700. color: (!isPip && this.currentLyricAlignMode === index) ||
  8701. (isPip && this.currentLyricAlignModePip === index) ?
  8702. '#007DFF' : '#DDDDDD',
  8703. width: 1.8
  8704. })
  8705. .onClick(() => {
  8706. this.setLyricAlignMode(index, isPip)
  8707. })
  8708. .margin({ left: 10, right: 8 })
  8709. })
  8710. }
  8711. .width('76%')
  8712. Blank()
  8713. }
  8714. .margin({
  8715. top: 10,
  8716. bottom: 10,
  8717. right: 20,
  8718. left: 20
  8719. })
  8720. if (isPip) {
  8721. Row() {
  8722. Text(`悬浮背景:`)
  8723. .fontSize(14)
  8724. .fontColor(Color.White)
  8725. Select([
  8726. { value: CommonConstants.PIP_LYRIC_BG[0] },
  8727. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  8728. .font({ size: 13, weight: FontWeight.Medium })
  8729. .fontColor(Color.White)
  8730. .margin({ left: 10 })
  8731. .selected(this.pipBgIndex)
  8732. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  8733. .onSelect(async (_index: number, text?: string | undefined) => {
  8734. this.pipBgIndex = _index
  8735. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  8736. if (this.pipBgIndex === 0) {
  8737. if (this.cover) {
  8738. this.pipBg = this.cover
  8739. } else {
  8740. this.pipBg = this.imageColor
  8741. }
  8742. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8743. } else {
  8744. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8745. }
  8746. })
  8747. Column() {
  8748. }
  8749. .backgroundColor(this.pipBg)
  8750. .margin({ left: 10, right: 10 })
  8751. .borderRadius(20)
  8752. .height(28)
  8753. .width(28)
  8754. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8755. Row() {
  8756. SymbolGlyph($r('sys.symbol.paintbrush'))
  8757. .fontColor([Color.White])
  8758. .effectStrategy(1)
  8759. Text(`选择颜色`)
  8760. .fontSize(13)
  8761. .margin({ left: 10 })
  8762. .fontColor(Color.White)
  8763. }
  8764. }
  8765. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  8766. .backgroundColor(Color.Transparent)
  8767. .border({
  8768. color: '#FFFFFF',
  8769. radius: 20,
  8770. width: 1.8
  8771. })
  8772. .height(36)
  8773. .width(110)
  8774. .onClick(() => {
  8775. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  8776. })
  8777. .bindPopup(this.isShowPipBgSelectColor, {
  8778. builder: this.SelectColor(false, isPip, true),
  8779. placement: Placement.Top,
  8780. mask: { color: '#33000000' },
  8781. enableArrow: false, //是否显示箭头
  8782. showInSubWindow: false,
  8783. onStateChange: (e) => {
  8784. if (!e.isVisible) {
  8785. this.isShowPipBgSelectColor = false
  8786. }
  8787. }
  8788. })
  8789. }
  8790. .width('76%')
  8791. .margin({ bottom: 5, right: 45, left: 20 })
  8792. }
  8793. if (!isPip) {
  8794. Row() {
  8795. Text(`高亮居中:`)
  8796. .fontSize(14)
  8797. .fontColor(Color.White)
  8798. Column() {
  8799. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  8800. .selectedColor(this.themeColor)
  8801. .switchPointColor(Color.White)
  8802. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8803. .onChange((checked: boolean) => {
  8804. this.isHightLightCenter = checked;
  8805. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  8806. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8807. })
  8808. .width(50)
  8809. .height(30)
  8810. .alignSelf(ItemAlign.Start)
  8811. .margin({ left: 12 })
  8812. Blank()
  8813. }
  8814. .width('76%')
  8815. }
  8816. .margin({
  8817. left: 20,
  8818. right: 15,
  8819. top: 10,
  8820. bottom: 10
  8821. })
  8822. }
  8823. Row() {
  8824. Text(`歌词颜色:`)
  8825. .fontSize(14)
  8826. .fontColor(Color.White)
  8827. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8828. .fontSize(15)
  8829. .fontColor(Color.White)
  8830. .margin({ left: 12, right: 12 })
  8831. Column() {
  8832. }
  8833. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8834. .margin({ right: 12 })
  8835. .borderRadius(20)
  8836. .height(28)
  8837. .width(28)
  8838. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8839. Row() {
  8840. SymbolGlyph($r('sys.symbol.paintbrush'))
  8841. .fontColor([Color.White])
  8842. .effectStrategy(1)
  8843. Text(`选择颜色`)
  8844. .fontSize(13)
  8845. .margin({ left: 10 })
  8846. .fontColor(Color.White)
  8847. }
  8848. }
  8849. .backgroundColor(Color.Transparent)
  8850. .border({
  8851. color: '#FFFFFF',
  8852. radius: 20,
  8853. width: 1.8
  8854. })
  8855. .height(36)
  8856. .width(110)
  8857. .onClick(() => {
  8858. this.isShowSelectColor = !this.isShowSelectColor
  8859. })
  8860. .bindPopup(this.isShowSelectColor, {
  8861. builder: this.SelectColor(false, isPip),
  8862. placement: Placement.Top,
  8863. mask: { color: '#33000000' },
  8864. enableArrow: false, //是否显示箭头
  8865. showInSubWindow: false,
  8866. onStateChange: (e) => {
  8867. if (!e.isVisible) {
  8868. this.isShowSelectColor = false
  8869. }
  8870. }
  8871. })
  8872. }
  8873. .width('76%')
  8874. .margin({
  8875. top: 10,
  8876. bottom: 10,
  8877. right: 45,
  8878. left: 20
  8879. })
  8880. Row() {
  8881. Text(`高亮颜色:`)
  8882. .fontSize(14)
  8883. .fontColor(Color.White)
  8884. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8885. .fontSize(15)
  8886. .fontColor(Color.White)
  8887. .margin({ left: 12, right: 12 })
  8888. Column() {
  8889. }
  8890. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8891. .margin({ right: 12 })
  8892. .borderRadius(20)
  8893. .height(28)
  8894. .width(28)
  8895. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8896. Row() {
  8897. SymbolGlyph($r('sys.symbol.paintbrush'))
  8898. .fontColor([Color.White])
  8899. .effectStrategy(1)
  8900. Text(`选择颜色`)
  8901. .fontSize(13)
  8902. .margin({ left: 10 })
  8903. .fontColor(Color.White)
  8904. }
  8905. }
  8906. .backgroundColor(Color.Transparent)
  8907. .border({
  8908. color: '#FFFFFF',
  8909. radius: 20,
  8910. width: 1.8
  8911. })
  8912. .height(36)
  8913. .width(110)
  8914. .onClick(() => {
  8915. this.isShowHLSelectColor = !this.isShowHLSelectColor
  8916. })
  8917. .bindPopup(this.isShowHLSelectColor, {
  8918. builder: this.SelectColor(true, isPip),
  8919. placement: Placement.Top,
  8920. mask: { color: '#33000000' },
  8921. enableArrow: false, //是否显示箭头
  8922. showInSubWindow: false,
  8923. onStateChange: (e) => {
  8924. if (!e.isVisible) {
  8925. this.isShowHLSelectColor = false
  8926. }
  8927. }
  8928. })
  8929. }
  8930. .width('76%')
  8931. .margin({
  8932. top: 10,
  8933. bottom: 10,
  8934. right: 45,
  8935. left: 20
  8936. })
  8937. if (isPip) {
  8938. Row() {
  8939. Text(`显示宽度:`)
  8940. .fontSize(14)
  8941. .fontColor(Color.White)
  8942. Slider({
  8943. value: this.pipLyWidth,
  8944. min: 10,
  8945. max: 800,
  8946. step: 1,
  8947. style: SliderStyle.OutSet
  8948. })
  8949. .blockColor(this.themeColor)
  8950. .trackColor($r('app.color.speed_text_color'))
  8951. .selectedColor(Color.White)
  8952. .trackThickness(6)
  8953. .onChange((value: number) => {
  8954. this.pipLyWidth = value
  8955. if (this.pipController) {
  8956. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8957. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  8958. }
  8959. })
  8960. .width('76%')
  8961. }
  8962. .margin({
  8963. left: 20,
  8964. right: 15,
  8965. top: 5,
  8966. bottom: 5
  8967. })
  8968. Row() {
  8969. Text(`显示高度:`)
  8970. .fontSize(14)
  8971. .fontColor(Color.White)
  8972. Slider({
  8973. value: this.pipLyHeight,
  8974. min: 10,
  8975. max: 1000,
  8976. step: 1,
  8977. style: SliderStyle.OutSet
  8978. })
  8979. .blockColor(this.themeColor)
  8980. .trackColor($r('app.color.speed_text_color'))
  8981. .selectedColor(Color.White)
  8982. .trackThickness(6)
  8983. .onChange((value: number) => {
  8984. this.pipLyHeight = value
  8985. if (this.pipController) {
  8986. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8987. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  8988. }
  8989. })
  8990. .width('76%')
  8991. }
  8992. .margin({
  8993. left: 20,
  8994. right: 15,
  8995. top: 5,
  8996. bottom: 5
  8997. })
  8998. }
  8999. Row() {
  9000. Text(`歌词字号:`)
  9001. .fontSize(14)
  9002. .fontColor(Color.White)
  9003. Slider({
  9004. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  9005. min: 12,
  9006. max: 30,
  9007. step: 0.1,
  9008. style: SliderStyle.OutSet
  9009. })
  9010. .blockColor(this.themeColor)
  9011. .trackColor($r('app.color.speed_text_color'))
  9012. .selectedColor(Color.White)
  9013. .trackThickness(6)
  9014. .onChange((value: number) => {
  9015. this.setLyricTextSize(value, isPip)
  9016. })
  9017. .width('76%')
  9018. }
  9019. .margin({
  9020. left: 20,
  9021. right: 15,
  9022. top: 5,
  9023. bottom: 5
  9024. })
  9025. Row() {
  9026. Text(`高亮倍数:`)
  9027. .fontSize(14)
  9028. .fontColor(Color.White)
  9029. Slider({
  9030. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  9031. min: 1,
  9032. max: 2,
  9033. step: 0.1,
  9034. style: SliderStyle.OutSet
  9035. })
  9036. .blockColor(this.themeColor)
  9037. .trackColor($r('app.color.speed_text_color'))
  9038. .selectedColor(Color.White)
  9039. .trackThickness(6)
  9040. .onChange((value: number) => {
  9041. this.setHighLyricTextSize(value, isPip)
  9042. })
  9043. .width('76%')
  9044. }
  9045. .margin({
  9046. left: 20,
  9047. right: 15,
  9048. top: 5,
  9049. bottom: 5
  9050. })
  9051. Row() {
  9052. Text(`歌词间隙:`)
  9053. .fontSize(14)
  9054. .fontColor(Color.White)
  9055. Slider({
  9056. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  9057. min: 0,
  9058. max: 100,
  9059. step: 1,
  9060. style: SliderStyle.OutSet
  9061. })
  9062. .blockColor(this.themeColor)
  9063. .trackColor($r('app.color.speed_text_color'))
  9064. .selectedColor(Color.White)
  9065. .trackThickness(6)
  9066. .onChange((value: number) => {
  9067. this.setLyricLineSpace(value, isPip)
  9068. })
  9069. .width('76%')
  9070. }
  9071. .margin({
  9072. left: 20,
  9073. right: 15,
  9074. top: 5,
  9075. bottom: 5
  9076. })
  9077. //取值间隔为100,默认为400,取值越大,字体越粗
  9078. Row() {
  9079. Text(`歌词字重:`)
  9080. .fontSize(14)
  9081. .fontColor(Color.White)
  9082. Slider({
  9083. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  9084. min: 100,
  9085. max: 900,
  9086. step: 100,
  9087. style: SliderStyle.OutSet
  9088. })
  9089. .blockColor(this.themeColor)
  9090. .trackColor($r('app.color.speed_text_color'))
  9091. .selectedColor(Color.White)
  9092. .trackThickness(6)
  9093. .onChange((value: number) => {
  9094. if (isPip) {
  9095. this.lyricTextWeightPip = value
  9096. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9097. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  9098. } else {
  9099. this.lyricTextWeight = value
  9100. this.lyricController.setTextWeight(this.lyricTextWeight)
  9101. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  9102. }
  9103. })
  9104. .width('76%')
  9105. }
  9106. .margin({
  9107. left: 20,
  9108. right: 15,
  9109. top: 5,
  9110. bottom: 5
  9111. })
  9112. if (!isPip) {
  9113. Row() {
  9114. Text(`歌词模糊:`)
  9115. .fontSize(14)
  9116. .fontColor(Color.White)
  9117. Slider({
  9118. value: isPip ? this.blurDegreePip : this.blurDegree,
  9119. min: 0,
  9120. max: 5,
  9121. step: 0.1,
  9122. style: SliderStyle.OutSet
  9123. })
  9124. .blockColor(this.themeColor)
  9125. .trackColor($r('app.color.speed_text_color'))
  9126. .selectedColor(Color.White)
  9127. .trackThickness(6)
  9128. .onChange((value: number) => {
  9129. this.setBlurDegree(value, isPip)
  9130. })
  9131. .width('76%')
  9132. }
  9133. .margin({
  9134. left: 20,
  9135. right: 15,
  9136. top: 5,
  9137. bottom: 15
  9138. })
  9139. }
  9140. Row() {
  9141. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  9142. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  9143. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  9144. }
  9145. .justifyContent(FlexAlign.Center)
  9146. .margin({ top: 3, bottom: 10 })
  9147. }
  9148. }
  9149. private setBlurDegree(index: number, isPip: boolean) {
  9150. if (isPip) {
  9151. this.blurDegreePip = index
  9152. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  9153. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  9154. } else {
  9155. this.blurDegree = index
  9156. this.lyricController.setBlurDegree(this.blurDegree)
  9157. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  9158. }
  9159. }
  9160. private setLyricAlignMode(index: number, isPip: boolean) {
  9161. if (isPip) {
  9162. this.currentLyricAlignModePip = index
  9163. if (this.currentLyricAlignModePip === 1) {
  9164. this.lyricControllerXF.setAlignMode("left")
  9165. } else {
  9166. this.lyricControllerXF.setAlignMode("center")
  9167. }
  9168. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  9169. } else {
  9170. this.currentLyricAlignMode = index
  9171. if (this.currentLyricAlignMode === 1) {
  9172. this.lyricController.setAlignMode("left")
  9173. } else {
  9174. this.lyricController.setAlignMode("center")
  9175. }
  9176. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  9177. }
  9178. }
  9179. private setLyricTextSize(index: number, isPip: boolean) {
  9180. if (isPip) {
  9181. this.currentLyricSizePip = index
  9182. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  9183. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  9184. } else {
  9185. this.currentLyricSize = index
  9186. this.lyricController.setTextSize(this.currentLyricSize)
  9187. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  9188. }
  9189. }
  9190. private setHighLyricTextSize(scale: number, isPip: boolean) {
  9191. if (isPip) {
  9192. this.currentHightLyricSizePip = scale
  9193. this.lyricControllerXF
  9194. .setHighlightScale(this.currentHightLyricSizePip)
  9195. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  9196. } else {
  9197. this.currentHightLyricSize = scale
  9198. this.lyricController
  9199. .setHighlightScale(this.currentHightLyricSize)
  9200. PreferencesUtil.putSync('HighLyricTextSize', scale)
  9201. }
  9202. }
  9203. private setLyricLineSpace(index: number, isPip: boolean) {
  9204. if (isPip) {
  9205. this.currentLyricLineSpacePip = index
  9206. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  9207. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  9208. } else {
  9209. this.currentLyricLineSpace = index
  9210. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  9211. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  9212. }
  9213. }
  9214. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  9215. LogUtil.info('onecold isBG = ' + isBG)
  9216. if (isBG) { //如果是设置悬浮背景
  9217. this.pipBg = color
  9218. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  9219. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9220. return
  9221. }
  9222. if (isPip) {
  9223. this.currentLyricColorPip = color
  9224. this.lyricControllerXF
  9225. .setTextColor(this.currentLyricColorPip)
  9226. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  9227. } else {
  9228. this.currentLyricColor = color
  9229. this.lyricController
  9230. .setTextColor(this.currentLyricColor)
  9231. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  9232. }
  9233. }
  9234. private changeLyricHightLightColor(color: string, isPip: boolean) {
  9235. if (isPip) {
  9236. this.currentHighLightLyricColorPip = color
  9237. this.lyricControllerXF
  9238. .setHighlightColor(this.currentHighLightLyricColorPip)
  9239. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  9240. } else {
  9241. this.currentHighLightLyricColor = color
  9242. this.lyricController
  9243. .setHighlightColor(this.currentHighLightLyricColor)
  9244. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  9245. }
  9246. }
  9247. // 构建时间控制器
  9248. @Builder
  9249. BuildTimeControls() {
  9250. Column() {
  9251. // 时间显示
  9252. Text(this.getTimeText())
  9253. .fontSize(18)
  9254. .fontColor(Color.White)
  9255. .margin({ bottom: 10 })
  9256. Row() {
  9257. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  9258. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  9259. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  9260. }
  9261. .justifyContent(FlexAlign.Center)
  9262. }
  9263. .margin({ top: 12, bottom: 8 })
  9264. }
  9265. // 精度按钮组件
  9266. @Builder
  9267. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  9268. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9269. Column() {
  9270. Image(icon)
  9271. .width(28)
  9272. .margin({ bottom: 5 })
  9273. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  9274. Text(label)
  9275. .fontSize(12)
  9276. .fontColor('#FFFFFF')
  9277. }
  9278. }
  9279. .backgroundColor(Color.Transparent)
  9280. .enabled(!this.isButtonDisabled(step))
  9281. .onClick(() => this.handlePrecisionAdjust(step))
  9282. .padding(5)
  9283. .width(66)
  9284. .height(66)
  9285. .margin({ left: 18, right: 18 })
  9286. .border({
  9287. color: '#FFFFFF',
  9288. width: 1.8
  9289. })
  9290. }
  9291. private handlePrecisionAdjust(step: number) {
  9292. if (step === 0) {
  9293. this.timeOffset = 0
  9294. return
  9295. }
  9296. // 精度处理:保留1位小数
  9297. const newOffset = Number((this.timeOffset + step).toFixed(5))
  9298. // 边界保护(±15.0秒)
  9299. if (newOffset < -30.0 || newOffset > 30.0) {
  9300. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  9301. return
  9302. }
  9303. // 状态更新
  9304. this.timeOffset = newOffset
  9305. }
  9306. // 按钮禁用逻辑
  9307. private isButtonDisabled(step: number): boolean {
  9308. const futureOffset = this.timeOffset + step
  9309. return (futureOffset < -30.0) || (futureOffset > 30.0)
  9310. }
  9311. // 时间显示文本升级
  9312. private getTimeText(): string {
  9313. const absValue = Math.abs(this.timeOffset)
  9314. return this.timeOffset === 0
  9315. ? '歌词时间已重置'
  9316. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  9317. }
  9318. // 导入 本地歌词 搜索歌词
  9319. @Builder
  9320. pushLyricButton(icon: Resource, step: number, label: string) {
  9321. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9322. Row() {
  9323. Image(icon)
  9324. .width(14)
  9325. .margin({ left: 13 })
  9326. Text(label)
  9327. .fontSize(12)
  9328. .margin({ left: 6 })
  9329. .fontColor('#FFFFFF')
  9330. }
  9331. }
  9332. .onClick(() => {
  9333. switch (step) {
  9334. case 0:
  9335. this.callFilePickerSelectFileForLyric()
  9336. break;
  9337. case 1:
  9338. //判断有没有设置api
  9339. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  9340. this.isLyricSetting = false
  9341. this.showTipsDialog()
  9342. return
  9343. }
  9344. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9345. ToastUtil.showToast('正在获取')
  9346. this.isLyricSetting = false
  9347. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9348. this.initLyric(lyricPath, true);
  9349. }
  9350. break;
  9351. }
  9352. })
  9353. .padding(5)
  9354. .width(110)
  9355. .backgroundColor(Color.Transparent)
  9356. .height(40)
  9357. .margin({ left: 6, right: 6 })
  9358. .border({
  9359. color: '#FFFFFF',
  9360. radius: 20,
  9361. width: 1.8
  9362. })
  9363. }
  9364. showVipDialog() {
  9365. DialogHelper.showCustomContentDialog({
  9366. dialogId: 'vip',
  9367. title: "友情提示",
  9368. autoCancel: false, //点击遮障层时,不关闭弹窗
  9369. backCancel: true, //点击返回键,不关闭弹窗
  9370. contentBuilder: () => {
  9371. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  9372. },
  9373. buttons: [],
  9374. })
  9375. }
  9376. //去赞助的自定义内容
  9377. @Builder
  9378. customVipBuilder(content: string) {
  9379. Column() {
  9380. Text(content)
  9381. .fontColor(Color.Gray)
  9382. .fontSize(16)
  9383. .alignSelf(ItemAlign.Start)
  9384. .margin({ bottom: 15 })
  9385. .fontSize(16)
  9386. Row() {
  9387. Button('取消')
  9388. .fontColor(Color.White)
  9389. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9390. .height(50)
  9391. .layoutWeight(1)
  9392. .stateEffect(true)
  9393. .margin({ right: 6 })
  9394. .onClick(() => {
  9395. DialogHelper.closeDialog('vip'); //关闭弹框
  9396. })
  9397. Button('开通')
  9398. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9399. .layoutWeight(1)
  9400. .height(50)
  9401. .backgroundColor(this.themeColor)
  9402. .stateEffect(true)
  9403. .margin({ left: 6 })
  9404. .onClick(() => {
  9405. DialogHelper.closeDialog('vip'); //关闭弹框
  9406. this.isShowPlay = false
  9407. this.mType = 1 //跳转到用户中心
  9408. // router.pushUrl({
  9409. // url: 'pages/VipPage'
  9410. // }, router.RouterMode.Single);
  9411. })
  9412. }
  9413. }
  9414. .width("100%")
  9415. .padding(10)
  9416. }
  9417. showTipsDialog() {
  9418. DialogHelper.showCustomContentDialog({
  9419. dialogId: 'tips',
  9420. title: "友情提示",
  9421. autoCancel: false, //点击遮障层时,不关闭弹窗
  9422. backCancel: true, //点击返回键,不关闭弹窗
  9423. contentBuilder: () => {
  9424. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  9425. },
  9426. buttons: [],
  9427. })
  9428. }
  9429. @Builder
  9430. customTipsBuilder(content: string) {
  9431. Column() {
  9432. Text(content)
  9433. .fontColor(Color.Gray)
  9434. .fontSize(16)
  9435. .alignSelf(ItemAlign.Start)
  9436. .margin({ bottom: 15 })
  9437. .fontSize(16)
  9438. Row() {
  9439. Button('取消')
  9440. .fontColor(Color.White)
  9441. .backgroundColor(this.themeColor)
  9442. .height(50)
  9443. .layoutWeight(1)
  9444. .stateEffect(true)
  9445. .margin({ right: 6 })
  9446. .onClick(() => {
  9447. DialogHelper.closeDialog('tips'); //关闭弹框
  9448. })
  9449. Button('跳转')
  9450. .fontColor(Color.White)//
  9451. .layoutWeight(1)
  9452. .height(50)
  9453. .backgroundColor(this.themeColor)
  9454. .stateEffect(true)
  9455. .margin({ left: 6 })
  9456. .onClick(() => {
  9457. DialogHelper.closeDialog('tips'); //关闭弹框
  9458. this.isShowEdit = false
  9459. this.longItemFilePath = ''
  9460. // if(this.isGridMusic&&!this.isShowPlay){
  9461. // this.longItemFilePath== ''
  9462. // }else{
  9463. // this.isShowEdit = false
  9464. // }
  9465. this.isShowMoreView = false;
  9466. this.isShowPlay = false
  9467. this.mType = 4
  9468. // router.pushUrl({
  9469. // url: 'pages/SettingPage'
  9470. // }, router.RouterMode.Single);
  9471. })
  9472. }
  9473. }
  9474. .width("100%")
  9475. .padding(10)
  9476. }
  9477. @Builder
  9478. PlayMoreSheet() {
  9479. Column() {
  9480. this.MoreList()
  9481. }
  9482. .width('100%')
  9483. .height('100%')
  9484. }
  9485. @Builder
  9486. MoreList() {
  9487. Scroll() {
  9488. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9489. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  9490. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9491. Row() {
  9492. if (more.id === 3&&this.currentSong) {
  9493. Image(more.image)
  9494. .width(24)
  9495. .height(24)
  9496. .margin({ left: 10, right: 10 })
  9497. Text(more.title)
  9498. .fontSize(16)
  9499. .fontColor(Color.White)
  9500. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  9501. height: this.isCoverOpacity() ? '95%' : '95%',
  9502. dragBar: true,
  9503. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9504. showClose: true,
  9505. blurStyle: BlurStyle.Thin,
  9506. backgroundColor: Color.Transparent,
  9507. title: { title: '歌曲信息' }
  9508. })
  9509. } else if (more.id === 15 && this.currentSong) { //编辑标签
  9510. Image(more.image)
  9511. .width(24)
  9512. .height(24)
  9513. .margin({ left: 10, right: 10 })
  9514. Text(more.title)
  9515. .fontSize(16)
  9516. .fontColor(Color.White)
  9517. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9518. height: '99%',
  9519. dragBar: true,
  9520. showClose: true,
  9521. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9522. // blurStyle:BlurStyle.Thin,
  9523. // backgroundColor:Color.Transparent,
  9524. title: { title: '编辑标签' }
  9525. })
  9526. } else if (more.id === 5) { //定时关闭
  9527. Image(more.image)
  9528. .width(24)
  9529. .height(24)
  9530. .margin({ left: 10, right: 10 })
  9531. Text(more.title)
  9532. .fontSize(16)
  9533. .fontColor(Color.White)
  9534. .onClick(() => {
  9535. this.doMore(more.id)
  9536. })
  9537. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  9538. height: this.isCoverOpacity() ? '95%' : '95%',
  9539. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9540. dragBar: true,
  9541. showClose: true,
  9542. title: { title: $r('app.string.time_close') }
  9543. })
  9544. } else if (more.id === 2) { //歌词设置
  9545. Image(more.image)
  9546. .width(24)
  9547. .height(24)
  9548. .margin({ left: 10, right: 10 })
  9549. Text(more.title)
  9550. .fontSize(16)
  9551. .fontColor(Color.White)
  9552. } else if (more.id === 16) { //悬浮歌词设置
  9553. Image(more.image)
  9554. .width(24)
  9555. .height(24)
  9556. .margin({ left: 10, right: 10 })
  9557. Text(more.title)
  9558. .fontSize(16)
  9559. .fontColor(Color.White)
  9560. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  9561. height: this.isCoverOpacity() ? '95%' : '95%',
  9562. dragBar: true,
  9563. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9564. showClose: true,
  9565. blurStyle: BlurStyle.Thin,
  9566. backgroundColor: Color.Transparent,
  9567. title: { title: '悬浮歌词' }
  9568. })
  9569. } else if (more.id === 11) {
  9570. Image(more.image)
  9571. .width(24)
  9572. .height(24)
  9573. .margin({ left: 10, right: 10 })
  9574. Text(more.title)
  9575. .fontSize(16)
  9576. .fontColor(Color.White)
  9577. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  9578. height: this.isCoverOpacity() ? '95%' : '60%',
  9579. dragBar: true,
  9580. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9581. showClose: true,
  9582. blurStyle: BlurStyle.Thin,
  9583. backgroundColor: Color.Transparent,
  9584. title: { title: '跳过头尾' }
  9585. })
  9586. } else if (more.id === 12) { //投播
  9587. AVCastPicker({
  9588. customPicker: (): void => this.TPImageBuilder(more),
  9589. onStateChange: (state) => {
  9590. if (state == AVCastPickerState.STATE_APPEARING) {
  9591. console.log(' The picker starts showing.');
  9592. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  9593. console.log(' The picker finishes presenting.');
  9594. }
  9595. },
  9596. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  9597. sessionType: 'video'
  9598. })
  9599. .id('AVCastPicker')
  9600. } else {
  9601. Image(more.image)
  9602. .width(24)
  9603. .height(24)
  9604. .margin({ left: 10, right: 10 })
  9605. .onClick(() => {
  9606. this.doMore(more.id)
  9607. })
  9608. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  9609. .fontSize(16)
  9610. .fontColor(Color.White)
  9611. .onClick(() => {
  9612. this.doMore(more.id)
  9613. })
  9614. Select([//倍速
  9615. { value: '0.25x' },
  9616. { value: '0.5x' },
  9617. { value: '0.75x' },
  9618. { value: '1x' },
  9619. { value: '1.25x' },
  9620. { value: '1.5x' },
  9621. { value: '1.75x' },
  9622. { value: '2x' },
  9623. { value: '3x' }])
  9624. .font({ size: 16, weight: FontWeight.Medium })
  9625. .fontColor($r('sys.color.white'))
  9626. .margin({ left: 25 })
  9627. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  9628. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  9629. .value(Utility.optimizedFormat(this.playSpeed))
  9630. .onSelect(async (_index: number, text?: string | undefined) => {
  9631. let speed = parseFloat(text?.replace('x', '') || '1');
  9632. if (!CommonConstants.video_speed_list.includes(speed)) {
  9633. speed = 1;
  9634. }
  9635. this.playSpeed = speed
  9636. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9637. })
  9638. Slider({
  9639. value: this.volume,
  9640. min: 0,
  9641. max: 1,
  9642. step: 0.1,
  9643. style: SliderStyle.OutSet
  9644. })
  9645. .margin({ left: 18, right: 8 })
  9646. .blockColor(this.themeColor)
  9647. .trackColor($r('app.color.speed_text_color'))
  9648. .selectedColor(Color.White)
  9649. .trackThickness(9)
  9650. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  9651. .onChange((value: number) => {
  9652. this.volume = value;
  9653. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9654. PreferencesUtil.putSync('DefalutVolume',this.volume)
  9655. })
  9656. .layoutWeight(1)
  9657. Blank()
  9658. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  9659. .selectedColor(this.themeColor)
  9660. .switchPointColor(Color.White)
  9661. .margin({ right: 15 })
  9662. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9663. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  9664. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9665. if (more.id == 6) {
  9666. this.isMusicMemoryPlay = checked;
  9667. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  9668. if (this.isMusicMemoryPlay) {
  9669. ToastUtil.showToast('记忆播放已开启')
  9670. } else {
  9671. ToastUtil.showToast('记忆播放已关闭')
  9672. }
  9673. }
  9674. })
  9675. .width(48)
  9676. .height(24);
  9677. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  9678. .selectedColor(this.themeColor)
  9679. .switchPointColor(Color.White)
  9680. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9681. .margin({ right: 15 })
  9682. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  9683. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9684. if (more.id == 7) {
  9685. this.isMusicBGCover = checked;
  9686. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  9687. if (this.isMusicBGCover) {
  9688. ToastUtil.showToast('播放背景随音乐封面已开启')
  9689. } else {
  9690. ToastUtil.showToast('播放背景随音乐封面已关闭')
  9691. }
  9692. }
  9693. })
  9694. .width(48)
  9695. .height(24);
  9696. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  9697. .selectedColor(this.themeColor)
  9698. .switchPointColor(Color.White)
  9699. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9700. .margin({ right: 15 })
  9701. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  9702. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9703. if (more.id == 8) {
  9704. this.isSavePlayMode = checked;
  9705. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  9706. if (this.isSavePlayMode) {
  9707. ToastUtil.showToast('保存播放模式已开启')
  9708. } else {
  9709. ToastUtil.showToast('保存播放模式已关闭')
  9710. }
  9711. }
  9712. })
  9713. .width(48)
  9714. .height(24);
  9715. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  9716. .selectedColor(this.themeColor)
  9717. .switchPointColor(Color.White)
  9718. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9719. .margin({ right: 15 })
  9720. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  9721. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9722. if (more.id == 13) {
  9723. this.isCoverRectangle = checked;
  9724. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  9725. if (this.isCoverRectangle) {
  9726. ToastUtil.showToast('封面方形已开启')
  9727. this.animationRoFun()
  9728. } else {
  9729. ToastUtil.showToast('封面圆形已开启')
  9730. this.animationRoFun()
  9731. }
  9732. }
  9733. })
  9734. .width(48)
  9735. .height(24);
  9736. }
  9737. }
  9738. .width('100%')
  9739. .height(45)
  9740. .padding(15)
  9741. .backgroundColor(Color.Transparent)
  9742. .borderRadius(12)
  9743. .margin({ bottom: 6 })
  9744. }
  9745. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  9746. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  9747. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  9748. .backgroundColor(Color.Transparent)
  9749. .onClick(() => {
  9750. this.doMore(more.id)
  9751. })
  9752. });
  9753. }
  9754. .width('100%')
  9755. .padding(16)
  9756. }.margin({ bottom: 18 })
  9757. }
  9758. @Builder
  9759. TPImageBuilder(more: MoreItem): void {
  9760. Row() {
  9761. Image($r('app.media.tuoping'))
  9762. .width(22)
  9763. .height(22)
  9764. .margin({ left: 10, right: 10 })
  9765. Text(more.title)
  9766. .fontSize(16)
  9767. .fontColor(Color.White)
  9768. }
  9769. .width('100%')
  9770. .layoutWeight(1)
  9771. .alignItems(VerticalAlign.Center)
  9772. .justifyContent(FlexAlign.Start)
  9773. }
  9774. private moreItems: MoreItem[] = [
  9775. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  9776. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  9777. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  9778. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  9779. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  9780. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  9781. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  9782. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  9783. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  9784. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  9785. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  9786. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  9787. { id: 4, image: $r('app.media.share2'), title: '分享' },
  9788. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  9789. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  9790. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  9791. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  9792. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  9793. ];
  9794. @State isShowMoreView: boolean = false;
  9795. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  9796. @State isShowTimeCloseMore: boolean = false
  9797. @State isShowDetailMore: boolean = false
  9798. @State isMusicBGCover: boolean = true
  9799. @State isSavePlayMode: boolean = true
  9800. @State isLyricSetting: boolean = false
  9801. @State isJumpSetting: boolean = false
  9802. @State isShowEdit: boolean = false
  9803. @State showPipLyric: boolean = false
  9804. async setRingTone() {
  9805. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  9806. return
  9807. }
  9808. // 确定后的逻辑
  9809. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  9810. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  9811. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  9812. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  9813. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  9814. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  9815. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  9816. , this.videoUrl, this.name).then(res => {
  9817. LogUtil.info('onecold setFlag :' + res);
  9818. });
  9819. }
  9820. doMore(moreId: number) {
  9821. switch (moreId) {
  9822. case 2: //歌词
  9823. this.isLyricSetting = !this.isLyricSetting;
  9824. this.isShowMoreView = false
  9825. break;
  9826. case 3: //详情
  9827. this.isShowDetailMore = !this.isShowDetailMore;
  9828. break;
  9829. case 4: //分享
  9830. if (this.currentSong !== undefined) {
  9831. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  9832. }
  9833. this.isShowMoreView = false
  9834. break;
  9835. case 5: //定时关闭
  9836. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  9837. break;
  9838. case 10: //设为铃声
  9839. this.setRingTone()
  9840. this.isShowMoreView = false
  9841. break;
  9842. case 11: //跳过头尾
  9843. this.isJumpSetting = !this.isJumpSetting;
  9844. break;
  9845. case 13: //倍速
  9846. break;
  9847. case 14: //搜索封面
  9848. if (this.currentSong !== undefined) {
  9849. this.doSearchCover(this.currentSong)
  9850. }
  9851. this.isShowMoreView = false
  9852. break;
  9853. case 15: //编辑标签
  9854. this.setEditStrEmpty()
  9855. this.tempLyricContent = this.lyricContent
  9856. this.isShowEdit = !this.isShowEdit;
  9857. break;
  9858. case 16: //悬浮歌词
  9859. this.showPipLyric = !this.showPipLyric;
  9860. break;
  9861. case 17: //横屏模式
  9862. if (this.isLandscape) {
  9863. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9864. } else {
  9865. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9866. }
  9867. this.isShowMoreView = false
  9868. break;
  9869. case 20://AB循环
  9870. this.isOpenAB = !this.isOpenAB;
  9871. this.isABSheet = false
  9872. break;
  9873. }
  9874. }
  9875. //AB循环
  9876. @State isOpenAB:boolean = false
  9877. @State jumpATime:number = 0
  9878. @State jumpBTime:number = 0
  9879. @State isABSheet:boolean = false
  9880. @Builder
  9881. ABLoopSheet() {
  9882. ABLoopComptent({
  9883. jumpATime:this.jumpATime,
  9884. jumpBTime:this.jumpBTime,
  9885. onClickAItem: async ()=>{
  9886. if(this.mIjkMediaPlayer){
  9887. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  9888. }
  9889. },
  9890. onClickBItem: async ()=>{
  9891. if(this.mIjkMediaPlayer){
  9892. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  9893. if(this.jumpBTime<=this.jumpATime){
  9894. ToastUtil.showToast('设置B点时间不能小于A点时间')
  9895. this.jumpBTime = 0
  9896. }
  9897. }
  9898. },
  9899. onCancleButtonClick: async ()=>{
  9900. this.isOpenAB = false
  9901. this.isABSheet = false
  9902. },
  9903. onStartButtonClick: async ()=>{
  9904. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  9905. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  9906. return
  9907. }
  9908. this.isABSheet = false
  9909. this.startABLoop()
  9910. },
  9911. })
  9912. }
  9913. //开始AB循环
  9914. startABLoop(){
  9915. if(this.mIjkMediaPlayer){
  9916. this.seekTo(this.jumpATime+'')
  9917. this.isOpenAB = true
  9918. }
  9919. }
  9920. /**
  9921. * 切换横竖屏
  9922. *
  9923. */
  9924. setOrientation(orientation: number) {
  9925. this.windowClass.setPreferredOrientation(orientation).then(() => {
  9926. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  9927. }).catch((err: BusinessError) => {
  9928. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  9929. });
  9930. }
  9931. /**
  9932. * 画中画功能(悬浮歌词功能)
  9933. *
  9934. */
  9935. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  9936. pipController?: PiPWindow.PiPController;
  9937. navigationId: string = '';
  9938. @State curState: string = '';
  9939. @State curError: ResourceStr = '';
  9940. @State pipBg: string = '#E8E8E8'
  9941. @State buttonAction: string = '';
  9942. //开启画中画功能
  9943. async startPip() {
  9944. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  9945. if (!this.pipController) {
  9946. await this.createPipController();
  9947. }
  9948. if (!this.pipController) {
  9949. Logger.info(`[${TAG}] pipController create error`);
  9950. return;
  9951. }
  9952. await this.pipController.startPiP();
  9953. }
  9954. async stopPip() {
  9955. if (!this.pipController) {
  9956. Logger.info(`[${TAG}] pipController is not exist`);
  9957. return;
  9958. }
  9959. this.isOpenPip = false
  9960. await this.pipController.stopPiP();
  9961. }
  9962. async createPipController() {
  9963. this.pipController = await PiPWindow.create({
  9964. context: getContext(this),
  9965. componentController: this.xcomponentController,
  9966. navigationId: this.navigationId,
  9967. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  9968. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  9969. customUIController: this.nodeController,
  9970. });
  9971. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  9972. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  9973. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9974. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  9975. this.onStateChange(state, reason);
  9976. });
  9977. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  9978. this.onActionEvent(event, status);
  9979. });
  9980. }
  9981. destroyPipController() {
  9982. if (!this.pipController) {
  9983. return;
  9984. }
  9985. this.pipController.off('stateChange');
  9986. this.pipController.off('controlPanelActionEvent');
  9987. this.pipController = undefined;
  9988. }
  9989. onStateChange(state: PiPWindow.PiPState, reason: string) {
  9990. switch (state) {
  9991. case PiPWindow.PiPState.ABOUT_TO_START:
  9992. this.curState = 'ABOUT_TO_START';
  9993. this.curError = $r('app.string.current_error_hint');
  9994. break;
  9995. case PiPWindow.PiPState.STARTED:
  9996. this.curState = 'STARTED';
  9997. this.curError = $r('app.string.current_error_hint');
  9998. break;
  9999. case PiPWindow.PiPState.ABOUT_TO_STOP:
  10000. this.curState = 'ABOUT_TO_STOP';
  10001. this.curError = $r('app.string.current_error_hint');
  10002. break;
  10003. case PiPWindow.PiPState.STOPPED:
  10004. this.curState = 'STOPPED';
  10005. this.curError = $r('app.string.current_error_hint');
  10006. this.stopPip()
  10007. this.destroyPipController()
  10008. break;
  10009. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  10010. this.curState = 'ABOUT_TO_RESTORE';
  10011. this.curError = $r('app.string.current_error_hint');
  10012. break;
  10013. case PiPWindow.PiPState.ERROR:
  10014. this.curState = 'ERROR';
  10015. this.curError = reason;
  10016. break;
  10017. default:
  10018. break;
  10019. }
  10020. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  10021. }
  10022. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  10023. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  10024. switch (event) {
  10025. case 'playbackStateChanged':
  10026. if (status === 0) {
  10027. this.pause();
  10028. } else {
  10029. console.info('onecold startPlayOrResumePlay 9869')
  10030. this.startPlayOrResumePlay();
  10031. }
  10032. break;
  10033. case 'nextVideo':
  10034. // 切换到下一个视频
  10035. this.playNext()
  10036. break;
  10037. case 'previousVideo':
  10038. // 切换到上一个视频
  10039. this.playPrevious()
  10040. break;
  10041. case 'previousVideo':
  10042. // 切换到上一个视频
  10043. this.playPrevious()
  10044. break;
  10045. default:
  10046. }
  10047. this.buttonAction = event + `-status:${status}`;
  10048. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  10049. }
  10050. /**
  10051. * 画中画功能(悬浮歌词功能)结束
  10052. *
  10053. */
  10054. async doSearchCover(item: VideoItem): Promise<string> {
  10055. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  10056. this.isShowMoreView = false;
  10057. this.showTipsDialog();
  10058. return ''; // Return empty string when no API is configured
  10059. }
  10060. if (!item) {
  10061. return ''; // Return empty string if item is undefined
  10062. }
  10063. const artist = item?.artist || ''; // Use empty string if artist is missing
  10064. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  10065. }
  10066. /**
  10067. *api搜索封面
  10068. *item,根据title和artist
  10069. */
  10070. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  10071. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  10072. LogUtil.debug("onecold res =" + res);
  10073. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10074. if (item.filePath == this.currentSong?.filePath) {
  10075. this.cover = res;
  10076. if (this.currentSong) {
  10077. this.currentSong.pixelMapPath = res;
  10078. }
  10079. }
  10080. // Update pixel map path but always return res regardless of success
  10081. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  10082. if (success) {
  10083. this.doUpdateData();
  10084. console.log("onecold 更新音乐封面成功,数据库已同步");
  10085. } else {
  10086. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  10087. }
  10088. // Note: We don't resolve/reject here because we already returned res
  10089. });
  10090. LogUtil.debug("onecold this.cover =" + this.cover);
  10091. }
  10092. return res; // Always return res regardless of updatePixelMapPath result
  10093. });
  10094. }
  10095. @State jumpTopTime: number = 0
  10096. @State jumpEndTime: number = 0
  10097. @State isOpenJump: boolean = false
  10098. @Builder
  10099. JumpTopEndSheet() {
  10100. Scroll() {
  10101. Column() {
  10102. Column() {
  10103. Text('仅对本播放列表有效')
  10104. .fontSize(16)
  10105. .fontColor($r('app.color.text_color'))
  10106. // 跳过头尾
  10107. Column() {
  10108. Row() {
  10109. Text('跳过片头:')
  10110. .fontSize(16)
  10111. .fontColor($r('app.color.text_color'))
  10112. Text(this.jumpTopTime + 's')
  10113. .fontSize(16)
  10114. .fontColor($r('app.color.text_color'))
  10115. }
  10116. .margin({ bottom: 5 })
  10117. Row() {
  10118. Slider({
  10119. value: this.jumpTopTime,
  10120. min: 0,
  10121. max: 120,
  10122. step: 1,
  10123. style: SliderStyle.OutSet
  10124. })
  10125. .blockColor(this.themeColor)
  10126. .trackColor($r('app.color.speed_text_color'))
  10127. .selectedColor(Color.White)
  10128. .trackThickness(8)
  10129. .onChange((value: number) => {
  10130. this.jumpTopTime = value;
  10131. })
  10132. .width('85%')
  10133. }
  10134. .alignItems(VerticalAlign.Top)
  10135. }
  10136. .margin({ top: 10, bottom: 10 })
  10137. // 跳过头尾
  10138. Column() {
  10139. Row() {
  10140. Text('跳过片尾:')
  10141. .fontSize(16)
  10142. .fontColor($r('app.color.text_color'))
  10143. Text(this.jumpEndTime + 's')
  10144. .fontSize(16)
  10145. .fontColor($r('app.color.text_color'))
  10146. }
  10147. .margin({ bottom: 5 })
  10148. Row() {
  10149. Slider({
  10150. value: this.jumpEndTime,
  10151. min: 0,
  10152. max: 120,
  10153. step: 1,
  10154. style: SliderStyle.OutSet
  10155. })
  10156. .blockColor(this.themeColor)
  10157. .trackColor($r('app.color.speed_text_color'))
  10158. .selectedColor(Color.White)
  10159. .trackThickness(8)
  10160. .onChange((value: number) => {
  10161. this.jumpEndTime = value;
  10162. })
  10163. .width('85%')
  10164. }
  10165. .alignItems(VerticalAlign.Top)
  10166. }
  10167. .margin({ top: 10, bottom: 10 })
  10168. Row() {
  10169. Button('保存设置')
  10170. .fontColor(Color.White)
  10171. .layoutWeight(1)
  10172. .height(40)
  10173. .width(80)
  10174. .backgroundColor(this.themeColor)
  10175. .stateEffect(true)
  10176. .margin({ left: 0, bottom: 20 })
  10177. .onClick(async () => {
  10178. if (!Utility.isNoble()) {
  10179. this.isJumpSetting = false
  10180. this.isShowMoreView = false
  10181. this.showVipDialog()
  10182. return
  10183. }
  10184. if (this.currentSong === undefined) {
  10185. return
  10186. }
  10187. if (this.modeType === 0) {
  10188. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10189. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  10190. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  10191. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  10192. } else if (this.modeType === 1) { //媒体库
  10193. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  10194. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  10195. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  10196. } else if (this.modeType === 2) { //艺术家
  10197. if (this.currentSong?.artist) {
  10198. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  10199. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  10200. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  10201. }
  10202. } else if (this.modeType === 3) { //专辑
  10203. if (this.currentSong?.album) {
  10204. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  10205. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  10206. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  10207. }
  10208. }
  10209. ToastUtil.showShort("保存成功")
  10210. this.isJumpSetting = false
  10211. })
  10212. }
  10213. .margin({
  10214. left: 38,
  10215. right: 38,
  10216. top: 10,
  10217. bottom: 10
  10218. })
  10219. .width(120)
  10220. .height(50)
  10221. }
  10222. }
  10223. }
  10224. .width('100%')
  10225. .height('100%')
  10226. }
  10227. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  10228. private onStateVastChange(state: AVCastPickerState) {
  10229. if (state == AVCastPickerState.STATE_APPEARING) {
  10230. console.log('The picker starts showing.');
  10231. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10232. console.log('The picker finishes presenting.');
  10233. }
  10234. }
  10235. private showSelectLyric() {
  10236. DialogHelper.showActionSheetDialog({
  10237. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  10238. // sheets: ["本地歌词", "搜索歌词"],
  10239. sheets: [
  10240. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  10241. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  10242. ],
  10243. maskColor: Color.Transparent,
  10244. backgroundColor: $r('app.color.bg_card'),
  10245. transition: AnimationHelper.transitionInDown(666),
  10246. onAction: (index) => {
  10247. switch (index) {
  10248. case 0:
  10249. this.callFilePickerSelectFileForLyric()
  10250. break;
  10251. case 1:
  10252. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10253. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10254. this.initLyric(lyricPath);
  10255. }
  10256. break;
  10257. }
  10258. }
  10259. })
  10260. }
  10261. // 拉起picker选择文件管理器
  10262. async callFilePickerSelectFileForLyric(): Promise<void> {
  10263. try {
  10264. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  10265. DocumentSelectOptions.maxSelectNumber = 1
  10266. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  10267. let documentPicker = new picker.DocumentViewPicker();
  10268. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  10269. Logger.info(TAG,
  10270. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  10271. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  10272. this.saveVideoDatasLyric(DocumentSelectResult)
  10273. }
  10274. }).catch((err: BusinessError) => {
  10275. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  10276. });
  10277. } catch (err) {
  10278. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  10279. }
  10280. }
  10281. async saveVideoDatasLyric(uris: string[]) {
  10282. if (ArrayUtil.isEmpty(uris)) {
  10283. return
  10284. }
  10285. let newUris: string[] = [];
  10286. for (let i = 0; i < uris.length; i++) {
  10287. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  10288. Logger.info(TAG, 'filePath uri: ' + filePath);
  10289. newUris.push(filePath)
  10290. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  10291. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  10292. fileIo.copyFileSync(file.fd, file2.fd)
  10293. fileIo.closeSync(file);
  10294. fileIo.closeSync(file2);
  10295. this.initLyric(filePath,false,false,true)
  10296. }
  10297. }
  10298. private initDelayPlay(context: object) {
  10299. this.mContext = context;
  10300. }
  10301. startPipLyric() {
  10302. if (this.pipController) {
  10303. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10304. PiPWindow.PiPControlStatus.PLAY);
  10305. }
  10306. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  10307. if (this.isOpenPip) {
  10308. this.startPip()
  10309. } else {
  10310. this.stopPip()
  10311. }
  10312. }
  10313. //startOffset 从cue分轨时间开始播
  10314. private startPlayOrResumePlay(startOffset?:number) {
  10315. //针对dsf文件高采样率sampleRate>441000,统一转wav播放
  10316. const sampleRate = this.currentSong?.sampleRate||0
  10317. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  10318. console.info('onecold 采样率 ='+sampleRate)
  10319. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  10320. console.info('onecold newDsfPath ='+newDsfPath)
  10321. if(!FileUtil.accessSync(newDsfPath)){
  10322. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  10323. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  10324. this.videoUrl = newDsfPath
  10325. this.startPlay(startOffset)
  10326. }).catch((e:object)=>{
  10327. console.info("task1 catch e: " + e);
  10328. })
  10329. }else{
  10330. this.videoUrl = newDsfPath
  10331. this.startPlay(startOffset)
  10332. }
  10333. }else{
  10334. this.startPlay(startOffset)
  10335. }
  10336. }
  10337. startPlay(startOffset?:number) {
  10338. this.startPipLyric()
  10339. this.mDestroyPage = false;
  10340. this.animationState = AnimationStatus.Running
  10341. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  10342. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10343. this.stopProgressTask();
  10344. this.startProgressTask();
  10345. this.play(this.videoUrl.toString(),startOffset);
  10346. }
  10347. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  10348. this.mIjkMediaPlayer.start();
  10349. this.setProgress()
  10350. this.CONTROL_PlayStatus = PlayStatus.PLAY
  10351. }
  10352. this.setIsPlaying(true)
  10353. this.updateSessionPlayState(true)
  10354. this.watchStatus();
  10355. this.updateLastPlayTimeStr(this.videoUrl)
  10356. }
  10357. updateLastPlayTimeStr(filePath: string) {
  10358. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  10359. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10360. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  10361. return;
  10362. }
  10363. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  10364. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  10365. if (success) {
  10366. this.getHistoryList(false)
  10367. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  10368. } else {
  10369. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  10370. }
  10371. });
  10372. }
  10373. private completionNum(num: number): string | number {
  10374. if (num < 10) {
  10375. return '0' + num;
  10376. } else {
  10377. return num;
  10378. }
  10379. }
  10380. private stringForTime(timeMs: number): string {
  10381. let totalSeconds: number | string = (timeMs / 1000);
  10382. let newSeconds: number | string = totalSeconds % 60;
  10383. let minutes: number | string = (totalSeconds / 60) % 60;
  10384. let hours: number | string = totalSeconds / 3600;
  10385. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  10386. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  10387. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  10388. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  10389. if (this.isCurrentTime) {
  10390. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  10391. this.oldSeconds = newSeconds
  10392. } else {
  10393. newSeconds = this.oldSeconds
  10394. }
  10395. }
  10396. newSeconds = this.completionNum(newSeconds);
  10397. if (hours > 0) {
  10398. return hours + ":" + minutes + ":" + newSeconds;
  10399. } else {
  10400. return minutes + ":" + newSeconds;
  10401. }
  10402. }
  10403. private setProgress() {
  10404. let position = this.mIjkMediaPlayer.getCurrentPosition();
  10405. let duration = this.mIjkMediaPlayer.getDuration();
  10406. let pos = 0;
  10407. if (duration > 0) {
  10408. this.slideEnable = true;
  10409. let curPercent = position / duration;
  10410. pos = curPercent * 100;
  10411. if (pos > this.PROGRESS_MAX_VALUE) {
  10412. this.progressValue = this.PROGRESS_MAX_VALUE
  10413. } else {
  10414. this.progressValue = pos;
  10415. }
  10416. }
  10417. // LogUtils.getInstance()
  10418. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10419. this.totalTime = this.stringForTime(duration);
  10420. if (position > duration) {
  10421. position = duration;
  10422. }
  10423. this.isCurrentTime = true;
  10424. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  10425. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  10426. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  10427. this.currentTime = this.stringForTime(position);
  10428. this.isCurrentTime = false
  10429. if (this.mIjkMediaPlayer.isPlaying()) {
  10430. this.randomColor =
  10431. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  10432. //如果是开启AB循环
  10433. if(this.isOpenAB){
  10434. if(position >=this.jumpBTime){
  10435. this.seekTo(this.jumpATime+'')
  10436. return
  10437. }
  10438. }
  10439. // 判断是否播放到结束时间
  10440. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  10441. if (position >= duration - this.jumpEndTime * 1000) {
  10442. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  10443. this.CONTROL_PlayStatus = PlayStatus.INIT
  10444. this.startPlayOrResumePlay();
  10445. }else if (this.playType == 2) { //2:正常播放,单曲播完
  10446. this.showRePlay();
  10447. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  10448. this.progressValue = this.PROGRESS_MAX_VALUE;
  10449. this.slideEnable = false;
  10450. this.stop();
  10451. // ToastUtil.showToast('开始重新播放')
  10452. }else{
  10453. this.playNext()
  10454. }
  10455. }
  10456. }
  10457. } else {
  10458. this.randomColor = 'rbg(0,0,0)'
  10459. }
  10460. }
  10461. private startProgressTask() {
  10462. let that = this;
  10463. this.updateProgressTimer = setInterval(() => {
  10464. //LogUtils.getInstance().LOGI("startProgressTask");
  10465. if (!that.mDestroyPage) {
  10466. that.setProgress();
  10467. }
  10468. }, 300);
  10469. }
  10470. private stopProgressTask() {
  10471. LogUtils.getInstance().LOGI("stopProgressTask");
  10472. clearInterval(this.updateProgressTimer);
  10473. }
  10474. private showLoadIng() {
  10475. this.loadingVisible = Visibility.Visible;
  10476. this.replayVisible = Visibility.None;
  10477. }
  10478. private hideLoadIng() {
  10479. this.loadingVisible = Visibility.None;
  10480. this.replayVisible = Visibility.None;
  10481. }
  10482. private showRePlay() {
  10483. this.loadingVisible = Visibility.None;
  10484. this.replayVisible = Visibility.Visible;
  10485. }
  10486. /**
  10487. * 为WebDAV请求添加认证头
  10488. */
  10489. private addWebDavAuthHeader(headers: Map<string, string>, accountId: number): void {
  10490. try {
  10491. // 从WebDAV管理器获取账户信息
  10492. const webdavManager = WebdavManager.getInstance();
  10493. const accounts = webdavManager.getAllWebDavAccounts();
  10494. const account = accounts.find(acc => acc.id === accountId);
  10495. if (account && account.account && account.password) {
  10496. // 构建Basic认证头
  10497. const credentials = `${account.account}:${account.password}`;
  10498. // 简单的Base64编码实现
  10499. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  10500. let encoded = '';
  10501. let i = 0;
  10502. while (i < credentials.length) {
  10503. const a = credentials.charCodeAt(i++);
  10504. const b = i < credentials.length ? credentials.charCodeAt(i++) : 0;
  10505. const c = i < credentials.length ? credentials.charCodeAt(i++) : 0;
  10506. const bitmap = (a << 16) | (b << 8) | c;
  10507. encoded += chars.charAt((bitmap >> 18) & 63);
  10508. encoded += chars.charAt((bitmap >> 12) & 63);
  10509. encoded += chars.charAt((bitmap >> 6) & 63);
  10510. encoded += chars.charAt(bitmap & 63);
  10511. }
  10512. // 处理剩余字符
  10513. const remainder = credentials.length % 3;
  10514. if (remainder === 1) {
  10515. const bitmap = credentials.charCodeAt(credentials.length - 1) << 16;
  10516. encoded += chars.charAt((bitmap >> 18) & 63);
  10517. encoded += chars.charAt((bitmap >> 12) & 63);
  10518. encoded += '==';
  10519. } else if (remainder === 2) {
  10520. const bitmap = (credentials.charCodeAt(credentials.length - 2) << 16) | (credentials.charCodeAt(credentials.length - 1) << 8);
  10521. encoded += chars.charAt((bitmap >> 18) & 63);
  10522. encoded += chars.charAt((bitmap >> 12) & 63);
  10523. encoded += chars.charAt((bitmap >> 6) & 63);
  10524. encoded += '=';
  10525. }
  10526. headers.set("Authorization", `Basic ${encoded}`);
  10527. Logger.info(`heanup 为WebDAV添加Basic认证头,账户: ${account.account}`);
  10528. } else {
  10529. Logger.warn(`heanup 未找到WebDAV账户信息或账户缺少认证信息,accountId: ${accountId}`);
  10530. }
  10531. } catch (error) {
  10532. Logger.error(`heanup 添加WebDAV认证头失败: ${error}`);
  10533. }
  10534. }
  10535. private async play(url: string,startOffset?:number) {
  10536. let that = this;
  10537. that.showLoadIng();
  10538. this.isOpenAB = false
  10539. //设置XComponent回调的context
  10540. if (!!this.mContext) {
  10541. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  10542. }
  10543. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10544. this.mIjkMediaPlayer.reset();
  10545. }
  10546. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  10547. //设置debug模式
  10548. this.mIjkMediaPlayer.setDebug(false);
  10549. //初始化配置
  10550. this.mIjkMediaPlayer.native_setup();
  10551. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  10552. if(this.volumeSmall){
  10553. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  10554. this.mIjkMediaPlayer.setVolume('1', '1');
  10555. }else{
  10556. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10557. }
  10558. }else{
  10559. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10560. }
  10561. //设置视频源
  10562. this.mIjkMediaPlayer.setDataSource(url);
  10563. //设置视频源http请求头
  10564. let headers = new Map([
  10565. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (ttmusic)"],
  10566. ["referer", "https://www.bilibili.com"]
  10567. ]);
  10568. // 如果是WebDAV网络音频,添加安全的HTTP头认证
  10569. if (this.currentSong&&this.currentSong.type === CommonConstants.TYPE_WEBDAV&&this.currentWebDavAuthInfo) {
  10570. headers = buildHttpHeadersWithWebDav(this.currentSong,this.videoUrl,this.currentWebDavAuthInfo)
  10571. }
  10572. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  10573. if (this.currentSong&&this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10574. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  10575. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  10576. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  10577. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  10578. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  10579. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  10580. // 缓冲和播放优化设置
  10581. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  10582. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  10583. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  10584. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  10585. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  10586. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  10587. // 网络相关设置
  10588. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  10589. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  10590. // 重连设置
  10591. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  10592. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  10593. }
  10594. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  10595. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  10596. // }
  10597. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10598. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  10599. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  10600. const fileSize = await this.getFileSize(this.videoUrl);
  10601. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  10602. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  10603. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  10604. }
  10605. // 使用软件解码(通常比硬件解码更节省内存)
  10606. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  10607. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  10608. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  10609. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  10610. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  10611. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  10612. //停止预读的最小帧数
  10613. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  10614. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  10615. // 设置其他缓冲相关选项
  10616. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  10617. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  10618. //启动预加载
  10619. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  10620. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  10621. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  10622. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  10623. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  10624. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  10625. // 因此需要播放器丢包,才不会累积延时
  10626. // 这个和第三个参数packet-buffering无关。
  10627. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  10628. // 无限制收流
  10629. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  10630. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  10631. // 屏幕常亮
  10632. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  10633. // 设置超时
  10634. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  10635. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  10636. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  10637. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  10638. // 变速播放
  10639. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  10640. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10641. let Speed = this.mIjkMediaPlayer.getSpeed()
  10642. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  10643. //是否开启循环播放
  10644. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  10645. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  10646. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  10647. if (height === 0) {
  10648. return;
  10649. }
  10650. const va = width / height;
  10651. const vpa = that.videoParentAspectRatio;
  10652. if (vpa > va) {
  10653. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  10654. } else {
  10655. that.videoWidth = '100%';
  10656. }
  10657. if (width && height) {
  10658. that.videoAspectRatio = width / height;
  10659. }
  10660. LogUtils.getInstance()
  10661. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  10662. that.hideLoadIng();
  10663. }
  10664. }
  10665. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  10666. let mOnPreparedListener: OnPreparedListener = {
  10667. onPrepared: async () => {
  10668. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  10669. try {
  10670. // this.cover = this.songList[this.curIndex].pixelMapPath
  10671. // this.artist = this.songList[this.curIndex].artist
  10672. // this.videoUrl = this.songList[this.curIndex].filePath
  10673. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10674. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  10675. this.setImageColor2(this.cover)
  10676. } else {
  10677. this.getImageColor();
  10678. }
  10679. //保存碰一碰分享的当前的歌曲
  10680. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  10681. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10682. await this.initLyric(lyricPath);
  10683. setTimeout(() => {
  10684. this.avSessionController.initAvSession(false);
  10685. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  10686. this.setAvSessionListener();
  10687. this.updateSessionPlayState(true)
  10688. this.setCurrentPlayMode()
  10689. }, 500)
  10690. if(startOffset&&startOffset>0){//cue分轨播放
  10691. this.seekTo(startOffset + "");
  10692. this.saveLastPlayList()
  10693. return
  10694. }
  10695. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10696. let timeoutPlay = 0
  10697. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10698. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  10699. timeoutPlay = 1000
  10700. }
  10701. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  10702. if (this.modeType === 0) { //文件夹
  10703. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10704. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  10705. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  10706. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  10707. } else if (this.modeType === 1) { //媒体库
  10708. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  10709. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  10710. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  10711. } else if (this.modeType === 2) { //艺术家
  10712. if (this.currentSong?.artist) {
  10713. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  10714. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  10715. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  10716. }
  10717. } else if (this.modeType === 3) { //专辑
  10718. if (this.currentSong?.album) {
  10719. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  10720. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  10721. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  10722. }
  10723. }
  10724. this.duration = this.mIjkMediaPlayer.getDuration()
  10725. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  10726. if (this.mIjkMediaPlayer != null) {
  10727. let jumpTopTimeMs = this.jumpTopTime*1000;
  10728. if (jumpTopTimeMs <= this.duration) {
  10729. // 调用 seekTo 方法,跳到指定时间
  10730. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  10731. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  10732. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10733. console.log('onecold position = '+position);
  10734. if (position > jumpTopTimeMs) {
  10735. jumpTopTimeMs = position
  10736. }
  10737. }
  10738. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10739. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10740. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  10741. }
  10742. }, timeoutPlay)
  10743. } else {
  10744. // 提示用户无法跳过
  10745. ToastUtil.showToast('跳过时间超过视频时长');
  10746. }
  10747. }
  10748. } else {
  10749. this.jumpTopTime = 0
  10750. this.jumpEndTime = 0
  10751. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  10752. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  10753. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  10754. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  10755. //记忆播放(每一首都会记忆播放)
  10756. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10757. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10758. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  10759. this.restorePlaybackPosition() //读取播放记忆功能
  10760. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  10761. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  10762. this.restorePlaybackPosition() //读取播放记忆功能
  10763. }
  10764. this.isFirstStartPlay = false
  10765. }, timeoutPlay)
  10766. } else {
  10767. this.isFirstStartPlay = false
  10768. }
  10769. }
  10770. this.saveLastPlayList()
  10771. } catch (error) {
  10772. let err: BusinessError = error as BusinessError;
  10773. console.error('onecold failed with err: ' + JSON.stringify(err));
  10774. }
  10775. }
  10776. }
  10777. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  10778. let mOnTimedTextListener: OnTimedTextListener = {
  10779. onTimedText: () => {
  10780. }
  10781. }
  10782. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  10783. let mOnCompletionListener: OnCompletionListener = {
  10784. onCompletion: () => {
  10785. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  10786. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  10787. this.playNext()
  10788. } else if (this.playType == 1) { //1:单片重复播放
  10789. this.CONTROL_PlayStatus = PlayStatus.INIT
  10790. console.info('onecold startPlayOrResumePlay 10592')
  10791. that.startPlayOrResumePlay();
  10792. } else if (this.playType == 2) { //2:正常播放,单曲播完
  10793. that.showRePlay();
  10794. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  10795. that.progressValue = this.PROGRESS_MAX_VALUE;
  10796. that.slideEnable = false;
  10797. that.stop();
  10798. // ToastUtil.showToast('开始重新播放')
  10799. } else if (this.playType == 3) { //3:随机播放
  10800. this.randomPlay()
  10801. }
  10802. }
  10803. }
  10804. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  10805. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  10806. onBufferingUpdate: (percent: number) => {
  10807. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  10808. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  10809. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  10810. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  10811. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  10812. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  10813. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  10814. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  10815. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  10816. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  10817. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  10818. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  10819. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  10820. let Looping = this.mIjkMediaPlayer.isLooping()
  10821. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  10822. }
  10823. }
  10824. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  10825. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  10826. onSeekComplete: () => {
  10827. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  10828. console.info('onecold startPlayOrResumePlay 10643')
  10829. that.startPlayOrResumePlay();
  10830. }
  10831. }
  10832. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  10833. let mOnInfoListener: OnInfoListener = {
  10834. onInfo: (what: number, extra: number) => {
  10835. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  10836. that.hideLoadIng();
  10837. }
  10838. }
  10839. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  10840. let mOnErrorListener: OnErrorListener = {
  10841. onError: (what: number, extra: number) => {
  10842. this.stopProgressTask();
  10843. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  10844. // 检查是否为WebDAV播放错误
  10845. let isWebDavError = false;
  10846. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV && this.currentSong.filePath) {
  10847. try {
  10848. const globalContext = GlobalContext.getContext();
  10849. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  10850. if (webDavAuthInfo) {
  10851. isWebDavError = true;
  10852. }
  10853. } catch (error) {
  10854. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  10855. }
  10856. }
  10857. if (isWebDavError) {
  10858. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  10859. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  10860. // this.currentWebDavAuthInfo = null;
  10861. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  10862. // 根据错误代码提供更具体的错误信息
  10863. let errorMessage = "WebDAV播放失败";
  10864. if (what === -1) { // 网络错误
  10865. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  10866. } else if (what === -1004) { // HTTP 404
  10867. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  10868. } else if (what === -1001) { // 超时
  10869. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  10870. } else if (what === -1003) { // 无法解析主机
  10871. errorMessage = "无法连接到WebDAV服务器";
  10872. }
  10873. ToastUtil.showToast(errorMessage);
  10874. } else {
  10875. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10876. !this.videoUrl.startsWith('http://') &&
  10877. !this.videoUrl.startsWith('https://') &&
  10878. !FileUtil.accessSync(this.videoUrl)) {
  10879. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  10880. } else {
  10881. ToastUtil.showToast(getContext()
  10882. .resourceManager
  10883. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  10884. }
  10885. }
  10886. that.hideLoadIng();
  10887. }
  10888. }
  10889. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  10890. this.mIjkMediaPlayer.setMessageListener();
  10891. this.mIjkMediaPlayer.prepareAsync();
  10892. this.mIjkMediaPlayer.start();
  10893. }
  10894. //保存最后播放的那首歌和已经对应的播放列表
  10895. saveLastPlayList() {
  10896. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  10897. PreferencesUtil.putSync('LastMusicList', this.songList)
  10898. }
  10899. // 清空播放记录
  10900. clearVideoHistory() {
  10901. this.table.clearPlayHistory((success: boolean, error?: string) => {
  10902. if (success) {
  10903. this.historyList = [];
  10904. this.updateListData(this.historyList)
  10905. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  10906. ToastUtil.showToast('清空播放记录成功')
  10907. } else {
  10908. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  10909. }
  10910. });
  10911. }
  10912. public async setAvSessionListener() {
  10913. if (!this.avSessionController) {
  10914. return;
  10915. }
  10916. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  10917. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  10918. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  10919. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  10920. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  10921. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  10922. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  10923. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  10924. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  10925. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  10926. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  10927. }
  10928. setLoopMode() {
  10929. let itype = this.playType + 1
  10930. if (itype >= 4) {
  10931. this.playType = 0
  10932. ToastUtil.showToast('连续播放')
  10933. } else if (itype === 1) {
  10934. this.playType = 1
  10935. ToastUtil.showToast('单曲循环')
  10936. } else if (itype === 2) {
  10937. this.playType = 2
  10938. ToastUtil.showToast('单曲播完')
  10939. } else if (itype === 3) {
  10940. this.playType = 3
  10941. ToastUtil.showToast('随机播放')
  10942. } else if (itype === 0) {
  10943. this.playType = 0
  10944. ToastUtil.showToast('连续播放')
  10945. }
  10946. PreferencesUtil.putSync('musicPlayType', this.playType)
  10947. this.setCurrentPlayMode()
  10948. }
  10949. private sessionSetLoopModeCallback = (mode: number) => {
  10950. if (this.mIjkMediaPlayer != null) {
  10951. ToastUtil.showToast('当前播放模式:' + mode)
  10952. Logger.info('onecold 当前播放模式= ' + mode)
  10953. let hmPlayMode = mode + 1
  10954. if (hmPlayMode >= 4) {
  10955. hmPlayMode = 0
  10956. }
  10957. if (hmPlayMode === 1) {
  10958. this.playType = 1
  10959. ToastUtil.showToast('单曲循环')
  10960. } else if (hmPlayMode === 0) {
  10961. this.playType = 2
  10962. ToastUtil.showToast('单曲播完')
  10963. } else if (hmPlayMode === 3) {
  10964. this.playType = 3
  10965. ToastUtil.showToast('随机播放')
  10966. } else if (hmPlayMode === 2) {
  10967. this.playType = 0
  10968. ToastUtil.showToast('连续播放')
  10969. }
  10970. PreferencesUtil.putSync('musicPlayType', this.playType)
  10971. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  10972. let playBackState: avSession.AVPlaybackState = {
  10973. loopMode: hmPlayMode,
  10974. };
  10975. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  10976. console.info(`set setLoopMode AVPlaybackState successfully`);
  10977. }).catch((err: BusinessError) => {
  10978. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  10979. });
  10980. }
  10981. }
  10982. setCurrentPlayMode() {
  10983. if (!this.avSessionController) {
  10984. return;
  10985. }
  10986. let mLoopMode = 0
  10987. switch (this.playType) {
  10988. case 0:
  10989. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  10990. break;
  10991. case 1:
  10992. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  10993. break;
  10994. case 2:
  10995. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  10996. break;
  10997. case 3:
  10998. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  10999. break;
  11000. }
  11001. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  11002. let playBState: avSession.AVPlaybackState = {
  11003. loopMode: mLoopMode,
  11004. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  11005. };
  11006. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  11007. console.info(`set setLoopMode AVPlaybackState successfully`);
  11008. }).catch((err: BusinessError) => {
  11009. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11010. });
  11011. }
  11012. private sessionToggleFavoriteCallback = (assetId: string) => {
  11013. if (this.mIjkMediaPlayer != null && this.currentSong) {
  11014. console.info(`on toggleFavorite `);
  11015. // 应用收到收藏命令,进行收藏处理。
  11016. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  11017. this.doFav(this.currentSong)
  11018. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  11019. let playbackState: avSession.AVPlaybackState = {
  11020. isFavorite: !this.isFac,
  11021. };
  11022. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  11023. console.info(`SetAVPlaybackState successfully`);
  11024. }).catch((err: BusinessError) => {
  11025. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  11026. });
  11027. }
  11028. }
  11029. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  11030. device: avSession.OutputDeviceInfo) => {
  11031. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  11032. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11033. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  11034. await this.startCasting();
  11035. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11036. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  11037. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  11038. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  11039. if (device) {
  11040. this.endCasting();
  11041. }
  11042. }
  11043. };
  11044. private async startCasting() {
  11045. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11046. this.setPlaybackStateChangeListener();
  11047. this.pause();
  11048. this.initQueueItem();
  11049. this.prepare();
  11050. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11051. refToIsCasting?.set(true);
  11052. this.castSeek = true;
  11053. this.isCastPlaying = true;
  11054. }
  11055. async changeCasting() {
  11056. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11057. this.initQueueItem();
  11058. this.prepare();
  11059. this.setPlaybackStateChangeListener();
  11060. this.isCastPlaying = true;
  11061. this.castSeek = true;
  11062. }
  11063. public endCasting() {
  11064. this.avSessionController.getAvSession()?.stopCasting();
  11065. this.stopCast();
  11066. this.isCastPlaying = false;
  11067. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11068. refToIsCasting?.set(false);
  11069. this.pause();
  11070. this.setIsPlaying(false);
  11071. // if (this.curIndex === this.curSource.index) {
  11072. // this.play
  11073. // this.seek(this.currentTime * 1000);
  11074. // this.setIsPlaying(true);
  11075. // } else {
  11076. // this.pauseVideo();
  11077. // this.setIsPlaying(false);
  11078. // }
  11079. }
  11080. public setIsPlaying(isPlayer: boolean) {
  11081. this.isPlaying = isPlayer;
  11082. // 发送播放状态变化事件给歌单详情页面
  11083. try {
  11084. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  11085. const currentFilePath = this.currentSong?.filePath || ''
  11086. const eventData: emitter.EventData = {
  11087. data: {
  11088. isPlaying: this.isPlaying,
  11089. curIndex: this.curIndex,
  11090. currentFilePath: currentFilePath
  11091. }
  11092. };
  11093. emitter.emit(eventPlaybackStatus, eventData)
  11094. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  11095. } catch (error) {
  11096. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  11097. }
  11098. }
  11099. private setPlaybackStateChangeListener(): void {
  11100. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  11101. this.castController?.on('endOfStream', this.reloadCasting);
  11102. this.castController?.on('playNext', this.playNextCallback);
  11103. this.castController?.on('playPrevious', this.playPreviousCallback);
  11104. }
  11105. private updateSessionPlayState(isPlay: boolean): void {
  11106. // if(!this.isBgPlayOpen)
  11107. // return
  11108. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  11109. this.setAVSessionPlayState({
  11110. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  11111. position: {
  11112. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  11113. updateTime: new Date().getTime()
  11114. }
  11115. });
  11116. }
  11117. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  11118. this.avSessionController.setAvSessionPlayState(playbackState)
  11119. }
  11120. private positionChange(position: number) {
  11121. this.currentTime2 = position / 1000;
  11122. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  11123. }
  11124. private playDurationChange(duration: number) {
  11125. this.duration = duration;
  11126. this.durationTime = Math.floor(this.duration / 1000);
  11127. this.durationStringTime = secondToTime((this.durationTime));
  11128. }
  11129. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  11130. const duration = playbackState?.extras?.duration;
  11131. if (typeof duration === 'number') {
  11132. this.playDurationChange(duration as number);
  11133. }
  11134. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  11135. this.positionChange(playbackState?.position?.elapsedTime);
  11136. }
  11137. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  11138. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  11139. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  11140. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  11141. this.isCastPlaying = false;
  11142. }
  11143. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  11144. this.isCastPlaying = true;
  11145. }
  11146. };
  11147. private reloadCasting = async () => {
  11148. let item = this.songList[this.curIndex];
  11149. let uri = fileUri.getUriFromPath(item.filePath);
  11150. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11151. // description.startPosition = 0;
  11152. this.castItem = {
  11153. itemId: this.curIndex,
  11154. description: {
  11155. assetId: item.filePath,
  11156. title: item.name,
  11157. artist: '',
  11158. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11159. // mediaUri: item.filePath,
  11160. fdSrc: {
  11161. fd: file.fd
  11162. },
  11163. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11164. mediaType: 'VIDEO',
  11165. mediaSize: item.videoSize,
  11166. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11167. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11168. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11169. duration: this.duration,
  11170. // albumCoverUri: 'https://www.example.jpeg',
  11171. // albumTitle: '《ExampleAlbum》',
  11172. appName: this.appName,
  11173. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11174. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11175. }
  11176. };
  11177. this.prepare();
  11178. this.isCastPlaying = true;
  11179. };
  11180. public playNextCallback = (): void => {
  11181. this.playNext()
  11182. };
  11183. public playPreviousCallback = (): void => {
  11184. this.playPrevious()
  11185. };
  11186. async prepare() {
  11187. await this.castController?.prepare(this.castItem);
  11188. await this.castController?.start(this.castItem);
  11189. }
  11190. public initQueueItem() {
  11191. let item = this.songList[this.curIndex];
  11192. let time = this.currentTime;
  11193. let uri = fileUri.getUriFromPath(item.filePath);
  11194. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11195. this.castItem = {
  11196. itemId: this.curIndex,
  11197. description: {
  11198. assetId: item.filePath,
  11199. title: item.name,
  11200. artist: '',
  11201. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11202. fdSrc: {
  11203. fd: file.fd
  11204. },
  11205. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11206. mediaType: 'AUDIO',
  11207. mediaSize: item.videoSize,
  11208. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11209. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11210. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11211. duration: this.duration,
  11212. // albumCoverUri: 'https://www.example.jpeg',
  11213. // albumTitle: '《ExampleAlbum》',
  11214. appName: this.appName,
  11215. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11216. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11217. }
  11218. };
  11219. }
  11220. async stopCast() {
  11221. try {
  11222. this.castController?.off('playbackStateChange');
  11223. this.castController?.off('endOfStream');
  11224. this.castController?.off('playNext');
  11225. this.castController?.off('playPrevious');
  11226. this.castController?.off('error');
  11227. } catch (error) {
  11228. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  11229. }
  11230. }
  11231. private sessionPlayCallback = (): void => {
  11232. console.info('onecold playOrPause 11050')
  11233. this.playOrPause()
  11234. };
  11235. private sessionPauseCallback = (): void => {
  11236. console.info('onecold playOrPause 11054')
  11237. this.pause()
  11238. };
  11239. private playOrPause() {
  11240. if (!this.debounce()) {
  11241. return;
  11242. }
  11243. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11244. this.pause();
  11245. } else {
  11246. console.info('onecold startPlayOrResumePlay 11064')
  11247. this.startPlayOrResumePlay();
  11248. this.playChange()
  11249. }
  11250. }
  11251. private sessionPlayNextCallback = (): void => {
  11252. this.playNext()
  11253. };
  11254. private sessionPlayPreviousCallback = (): void => {
  11255. this.playPrevious()
  11256. };
  11257. private sessionStopCallback = (): void => {
  11258. this.stop()
  11259. };
  11260. private sessionFastForwardCallback = (time?: number) => {
  11261. if (!time) {
  11262. return;
  11263. }
  11264. if (this.mIjkMediaPlayer != null) {
  11265. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11266. let seeTime = curPosition + time * 1000;
  11267. // 限制 seekValue 在合法范围内
  11268. if (seeTime < 0) {
  11269. seeTime = 0;
  11270. } else if (seeTime > this.duration) {
  11271. seeTime = this.duration;
  11272. }
  11273. Logger.info('onecold seeTime= ' + seeTime)
  11274. this.setSeekToActionProgress(seeTime)
  11275. this.seekTo(seeTime + "")
  11276. }
  11277. };
  11278. /**
  11279. * Gesture method onActionUpdate.
  11280. *
  11281. * @param event Gesture event.手势拖动设置快进和后退
  11282. */
  11283. private setSeekToActionProgress(position: number) {
  11284. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  11285. let duration = this.mIjkMediaPlayer.getDuration();
  11286. let pos = 0;
  11287. if (duration > 0) {
  11288. this.slideEnable = true;
  11289. let curPercent = position / duration;
  11290. pos = curPercent * 100;
  11291. if (pos > this.PROGRESS_MAX_VALUE) {
  11292. this.progressValue = this.PROGRESS_MAX_VALUE
  11293. } else {
  11294. this.progressValue = pos;
  11295. }
  11296. }
  11297. // LogUtils.getInstance()
  11298. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11299. this.totalTime = this.stringForTime(duration);
  11300. if (position > duration) {
  11301. position = duration;
  11302. }
  11303. this.isCurrentTime = true;
  11304. this.currentTime = this.stringForTime(position);
  11305. this.isCurrentTime = false
  11306. }
  11307. private sessionRewindCallback = (time?: number) => {
  11308. if (!time) {
  11309. return;
  11310. }
  11311. if (this.mIjkMediaPlayer != null) {
  11312. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11313. let seeTime = curPosition - time * 1000;
  11314. // 限制 seekValue 在合法范围内
  11315. if (seeTime < 0) {
  11316. seeTime = 0;
  11317. } else if (seeTime > this.duration) {
  11318. seeTime = this.duration;
  11319. }
  11320. Logger.info('onecold seeTime= ' + seeTime)
  11321. this.setSeekToActionProgress(seeTime)
  11322. this.seekTo(seeTime + "")
  11323. }
  11324. };
  11325. private sessionSeekCallback = (seekTime: number) => {
  11326. if (this.mIjkMediaPlayer != null) {
  11327. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11328. this.seekTo(seekTime + "")
  11329. }
  11330. };
  11331. private async getFileSize(filePath: string): Promise<number> {
  11332. try {
  11333. const stat = await fs.stat(filePath);
  11334. return stat.size;
  11335. } catch (err) {
  11336. console.error('Failed to get file size: ' + err.message);
  11337. return 0;
  11338. }
  11339. }
  11340. private pause() {
  11341. if (this.mIjkMediaPlayer.isPlaying()) {
  11342. this.savePlaybackPosition();
  11343. this.mIjkMediaPlayer.pause();
  11344. this.setProgress();
  11345. this.mDestroyPage = true;
  11346. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  11347. this.updateSessionPlayState(false)
  11348. this.playChange()
  11349. if (this.pipController) {
  11350. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11351. PiPWindow.PiPControlStatus.PAUSE);
  11352. }
  11353. }
  11354. }
  11355. private stop() {
  11356. this.savePlaybackPosition();
  11357. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11358. this.mIjkMediaPlayer.stop();
  11359. this.mIjkMediaPlayer.release();
  11360. this.stopProgressTask();
  11361. this.updateSessionPlayState(false)
  11362. this.playChange()
  11363. this.watchStatus();
  11364. }
  11365. //保持记忆播放功能
  11366. private savePlaybackPosition() {
  11367. if (this.mIjkMediaPlayer != null) {
  11368. const position = this.mIjkMediaPlayer.getCurrentPosition();
  11369. // ToastUtil.showToast('保存记忆播放 = ' + position)
  11370. const duration = this.mIjkMediaPlayer.getDuration();
  11371. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  11372. // 如果播放位置接近视频末尾,则保存 position 为 0
  11373. const playbackPosition = (duration - position < threshold) ? 0 : position;
  11374. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  11375. }
  11376. }
  11377. //获取记忆播放功能
  11378. private restorePlaybackPosition() {
  11379. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11380. // ToastUtil.showToast('position = ' + position)
  11381. if (this.mIjkMediaPlayer != null && position > 0) {
  11382. // ToastUtil.showToast('seekTo = ' + position)
  11383. this.seekTo(position + "");
  11384. }
  11385. }
  11386. private seekTo(value: string) {
  11387. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  11388. ToastUtil.showToast('wma格式不支持拖动快进。')
  11389. return
  11390. }
  11391. this.isSeekTo = true
  11392. this.mIjkMediaPlayer.seekTo(value);
  11393. console.info('onecold startPlayOrResumePlay 11227')
  11394. // this.startPlayOrResumePlay()
  11395. // 在这里恢复计时器状态
  11396. this.setProgress()
  11397. this.isSeekTo = false
  11398. }
  11399. // 添加到下一首播放
  11400. private addToNextPlay(song: VideoItem) {
  11401. if (!this.debounce()) {
  11402. return;
  11403. }
  11404. if (this.currentSong) {
  11405. if (this.currentSong === song) {
  11406. ToastUtil.showToast('当前已经在播放这首歌了!')
  11407. return
  11408. }
  11409. }
  11410. // 如果未开始播放或队列为空
  11411. if (this.curIndex === -1 || this.songList.length === 0) {
  11412. this.songList = [song];
  11413. this.curIndex = 0;
  11414. this.doPlay(song)
  11415. return;
  11416. }
  11417. // 插入到当前索引+1的位置
  11418. const insertPos = this.curIndex + 1;
  11419. this.songList.splice(insertPos, 0, song);
  11420. this.songList = [...this.songList]; // 触发状态更新
  11421. this.sonDataSource.pushArrayData(this.songList)
  11422. ToastUtil.showToast('已添加至下一首播放')
  11423. }
  11424. //后退10s,可再设置设置默认几秒
  11425. backForward() {
  11426. if(this.mIjkMediaPlayer){
  11427. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11428. let value = pos - Number(this.fastForwardSeconds) * 1000;
  11429. this.seekTo(value+"");
  11430. }
  11431. }
  11432. //快进10s,可再设置设置默认几秒
  11433. fastForward() {
  11434. if(this.mIjkMediaPlayer){
  11435. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11436. let value = pos + Number(this.fastForwardSeconds) * 1000;
  11437. this.seekTo(value+"");
  11438. }
  11439. }
  11440. //下一个
  11441. private playNext() {
  11442. if (!this.debounce()) {
  11443. return;
  11444. }
  11445. if (this.playType == 3) { //3:随机播放
  11446. this.randomPlay()
  11447. return;
  11448. }
  11449. if (ArrayUtil.isNotEmpty(this.songList)) {
  11450. if (this.curIndex == this.songList.length - 1) {
  11451. this.curIndex = 0;
  11452. } else {
  11453. this.curIndex++;
  11454. }
  11455. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11456. this.stop();
  11457. this.currentSong = this.songList[this.curIndex]
  11458. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11459. this.artist = this.songList[this.curIndex].artist
  11460. this.name = this.songList[this.curIndex].name
  11461. //this.cover = this.songList[this.curIndex].pixelMapPath
  11462. this.changeImageAnimation()
  11463. }
  11464. }
  11465. changeImageAnimation() {
  11466. if(this.openSkipSongAnimate){
  11467. // 第一步:淡出动画
  11468. this.getUIContext()?.animateTo({
  11469. duration: 500,
  11470. curve: Curve.EaseOut,
  11471. }, () => {
  11472. this.opacityValueImage = 0.1;
  11473. if(this.isCoverRectangle){
  11474. this.scaleValueImage = 0.88
  11475. }
  11476. });
  11477. // 第二步:切换图片后淡入
  11478. setTimeout(() => {
  11479. this.cover = this.songList[this.curIndex].pixelMapPath
  11480. this.getUIContext()?.animateTo({
  11481. duration: 500,
  11482. curve: Curve.EaseIn,
  11483. }, () => {
  11484. this.opacityValueImage = 1;
  11485. this.scaleValueImage = 1 // 图标恢复到原始大小
  11486. this.startPlayOrResumePlay()
  11487. });
  11488. }, 500);
  11489. }else{
  11490. this.cover = this.songList[this.curIndex].pixelMapPath
  11491. this.startPlayOrResumePlay()
  11492. }
  11493. }
  11494. // 存储已播放的歌曲索引
  11495. private playedIndices: Set<number> = new Set();
  11496. //随机播放
  11497. private randomPlay() {
  11498. // if (!this.debounce()) {
  11499. // return;
  11500. // }
  11501. if (ArrayUtil.isNotEmpty(this.songList)) {
  11502. if (this.songList.length > 3) {
  11503. // 如果所有歌曲都播放过一次,清空已播放索引集合
  11504. if (this.playedIndices.size === this.songList.length) {
  11505. this.playedIndices.clear();
  11506. }
  11507. // 随机选择一个未播放的歌曲索引
  11508. let newIndex: number;
  11509. // 添加超时机制防止无限循环
  11510. let attempt = 0;
  11511. const maxAttempts = 100; // 根据需求调整
  11512. do {
  11513. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  11514. attempt++;
  11515. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  11516. if (attempt >= maxAttempts) {
  11517. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  11518. newIndex = Math.floor(Math.random() * this.songList.length);
  11519. }
  11520. this.curIndex = newIndex;
  11521. this.playedIndices.add(newIndex);
  11522. } else {
  11523. // 当歌曲数量小于或等于3时,直接播放下一首
  11524. if (this.curIndex == this.songList.length - 1) {
  11525. this.curIndex = 0;
  11526. } else {
  11527. this.curIndex++;
  11528. }
  11529. }
  11530. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11531. this.stop();
  11532. this.currentSong = this.songList[this.curIndex];
  11533. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11534. this.name = this.songList[this.curIndex].name;
  11535. this.artist = this.songList[this.curIndex].artist
  11536. // this.cover = this.songList[this.curIndex].pixelMapPath
  11537. this.changeImageAnimation()
  11538. }
  11539. }
  11540. private playIndex(index: number) {
  11541. if (!this.debounce()) {
  11542. return;
  11543. }
  11544. if (ArrayUtil.isNotEmpty(this.songList)) {
  11545. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11546. this.stop();
  11547. this.currentSong = this.songList[this.curIndex]
  11548. this.videoUrl = this.songList[index].filePath.replace(/ /g, '%20');
  11549. this.name = this.songList[index].name
  11550. this.artist = this.songList[this.curIndex].artist
  11551. this.curIndex = index;
  11552. this.changeImageAnimation()
  11553. }
  11554. }
  11555. //上一个
  11556. private playPrevious() {
  11557. if (!this.debounce()) {
  11558. return;
  11559. }
  11560. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  11561. this.randomModePlayFromHistory()
  11562. return;
  11563. }
  11564. if (this.curIndex == 0) {
  11565. this.curIndex = this.songList.length - 1;
  11566. } else {
  11567. this.curIndex--;
  11568. }
  11569. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11570. this.stop();
  11571. this.currentSong = this.songList[this.curIndex]
  11572. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11573. this.name = this.songList[this.curIndex].name
  11574. this.artist = this.songList[this.curIndex].artist
  11575. this.changeImageAnimation()
  11576. }
  11577. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  11578. private randomModePlayFromHistory() {
  11579. if (this.historyList.length >= 2) {
  11580. // 播放历史记录的第二首
  11581. const prevSong = this.historyList[1];
  11582. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  11583. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11584. this.stop();
  11585. this.currentSong = prevSong;
  11586. this.videoUrl = prevSong.filePath.replace(/ /g, '%20');
  11587. this.cover = prevSong.pixelMapPath
  11588. this.artist = prevSong.artist
  11589. this.name = prevSong.name;
  11590. console.info('onecold startPlayOrResumePlay 11434')
  11591. this.startPlayOrResumePlay();
  11592. } else {
  11593. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  11594. if (this.curIndex === 0) {
  11595. this.curIndex = this.songList.length - 1;
  11596. } else {
  11597. this.curIndex--;
  11598. }
  11599. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11600. this.stop();
  11601. this.currentSong = this.songList[this.curIndex];
  11602. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11603. this.artist = this.songList[this.curIndex].artist
  11604. this.name = this.songList[this.curIndex].name;
  11605. this.changeImageAnimation()
  11606. }
  11607. }
  11608. debounce() {
  11609. const delay = 600;
  11610. let cur = new Date().getTime();
  11611. if (cur - this.last > delay) {
  11612. this.last = cur;
  11613. return true;
  11614. }
  11615. return false;
  11616. }
  11617. /**
  11618. * Sets whether the screen is a constant based on the playback status.
  11619. */
  11620. watchStatus() {
  11621. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  11622. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11623. this.windowClass.setWindowKeepScreenOn(true);
  11624. } else {
  11625. this.windowClass.setWindowKeepScreenOn(false);
  11626. }
  11627. }
  11628. /**
  11629. * Volume gesture method onActionStart.
  11630. *
  11631. * @param event Gesture event.
  11632. */
  11633. private customDialogComponentIdMM: number = 0
  11634. @Builder
  11635. customDialogComponentMM() {
  11636. Column() {
  11637. Row() {
  11638. Blank()
  11639. Text('验证密码')
  11640. .fontSize(22)
  11641. .fontColor($r('app.color.pri_bg'))
  11642. .margin({ top: 18 })
  11643. Blank()
  11644. Image($r('app.media.close'))
  11645. .fillColor(Color.White)
  11646. .margin({ top: 18, right: 18 })
  11647. .width(20)
  11648. .onClick(() => {
  11649. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11650. })
  11651. }
  11652. .width('100%') // 使Row占据整个宽度
  11653. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  11654. Verify({
  11655. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  11656. });
  11657. }.height('60%')
  11658. .backgroundColor($r('app.color.index_background'))
  11659. .justifyContent(FlexAlign.SpaceBetween)
  11660. }
  11661. private handleVerifyCompleted(isSuccess: boolean) {
  11662. if (isSuccess) {
  11663. console.log('验证成功');
  11664. // 在这里处理验证成功后的逻辑
  11665. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11666. this.currentPath = this.lockPath
  11667. this.getSortedFiles(this.currentPath)
  11668. } else {
  11669. // console.log('验证失败');
  11670. ToastUtil.showToast('验证失败')
  11671. }
  11672. }
  11673. private showVerifyDialog() {
  11674. promptAction.openCustomDialog({
  11675. transition: TransitionEffect.asymmetric(
  11676. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  11677. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11678. ,
  11679. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  11680. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11681. ),
  11682. builder: () => {
  11683. this.customDialogComponentMM()
  11684. },
  11685. isModal: true,
  11686. autoCancel: true,
  11687. maskColor: Color.Transparent,
  11688. alignment: DialogAlignment.Bottom,
  11689. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  11690. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  11691. console.log("dialog onWillDismiss")
  11692. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  11693. dismissDialogAction.dismiss()
  11694. }
  11695. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  11696. dismissDialogAction.dismiss()
  11697. }
  11698. }
  11699. }).then((dialogId: number) => {
  11700. this.customDialogComponentIdMM = dialogId
  11701. })
  11702. }
  11703. //左滑操作 移动文件 重命名 删除等操作
  11704. @Builder
  11705. DeleteButton(item: VideoItem, index: number, filePath: string) {
  11706. Row() {
  11707. //加入收藏
  11708. Button() {
  11709. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  11710. .fillColor(Color.White)
  11711. .width(20)
  11712. }
  11713. .width(40)
  11714. .height(40)
  11715. .type(ButtonType.Circle)
  11716. .backgroundColor(this.themeColor)
  11717. .margin(5)
  11718. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11719. .onClick(() => {
  11720. if (item) {
  11721. this.doFav(item)
  11722. }
  11723. })
  11724. //加入下一首播放
  11725. Button() {
  11726. Image($r('app.media.next_to_play'))
  11727. .fillColor(Color.White)
  11728. .width(20)
  11729. }
  11730. .width(40)
  11731. .height(40)
  11732. .type(ButtonType.Circle)
  11733. .backgroundColor(this.themeColor)
  11734. .margin(5)
  11735. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11736. .onClick(() => {
  11737. this.addToNextPlay(item);
  11738. })
  11739. //复制文件
  11740. Button() {
  11741. Image($r('app.media.copy'))
  11742. .fillColor(Color.White)
  11743. .width(20)
  11744. }
  11745. .width(40)
  11746. .height(40)
  11747. .type(ButtonType.Circle)
  11748. .backgroundColor(this.themeColor)
  11749. .margin(5)
  11750. .id(filePath + 'copy')
  11751. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11752. .onClick(() => {
  11753. this.showCopyDialog(false, item, index, filePath + 'copy');
  11754. })
  11755. //移动文件
  11756. Button() {
  11757. Image($r('app.media.cut'))
  11758. .fillColor(Color.White)
  11759. .width(20)
  11760. }
  11761. .width(40)
  11762. .height(40)
  11763. .type(ButtonType.Circle)
  11764. .backgroundColor(this.themeColor)
  11765. .margin(5)
  11766. .id(filePath)
  11767. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11768. .onClick(() => {
  11769. this.showCutDialog(false, item, index, filePath);
  11770. })
  11771. Button() {
  11772. Image($r('app.media.cut_current'))
  11773. .fillColor(Color.White)
  11774. .width(20)
  11775. }
  11776. .width(40)
  11777. .height(40)
  11778. .type(ButtonType.Circle)
  11779. .backgroundColor(this.themeColor)
  11780. .margin(5)
  11781. .id(filePath + 'current')
  11782. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  11783. (this.isHasDir ? Visibility.Visible : Visibility.None))
  11784. .onClick(() => {
  11785. this.showCutDialog(true, item, index, filePath + 'current');
  11786. })
  11787. //重命名
  11788. Button() {
  11789. Image($r('app.media.rename2'))
  11790. .fillColor(Color.White)
  11791. .width(20)
  11792. }
  11793. .width(40)
  11794. .height(40)
  11795. .type(ButtonType.Circle)
  11796. .backgroundColor(this.themeColor)
  11797. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11798. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11799. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11800. .margin(5)
  11801. .onClick(() => {
  11802. this.showReNameDialog(item, index + '', filePath)
  11803. })
  11804. Button() {
  11805. Image($r('app.media.delete2'))
  11806. .fillColor(Color.White)
  11807. .width(20)
  11808. }
  11809. .width(40)
  11810. .height(40)
  11811. .type(ButtonType.Circle)
  11812. .backgroundColor(this.themeColor)
  11813. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11814. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11815. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11816. .margin(5)
  11817. .onClick(() => {
  11818. this.selectedFiles.push(item)
  11819. this.showWarnIsDelete()
  11820. // this.showWarnIsDeleteFile(item, index + '', filePath)
  11821. })
  11822. Button() {
  11823. Image($r('app.media.share2'))
  11824. .fillColor(Color.White)
  11825. .width(20)
  11826. }
  11827. .width(40)
  11828. .height(40)
  11829. .type(ButtonType.Circle)
  11830. .backgroundColor(this.themeColor)
  11831. .margin(5)
  11832. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11833. .onClick(() => {
  11834. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11835. })
  11836. }
  11837. }
  11838. /**
  11839. * 穿山甲banner广告
  11840. */
  11841. // private declare bannerAd: CSJNativeExpressAd;
  11842. // @State private status: string = "未加载"
  11843. // @State private isShowAd: boolean = false
  11844. // private declare mAdSlot: AdSlot;
  11845. // private mBiddingAdm = '' //服务端bidding才需要设置
  11846. // private expressLoadAdListener: NativeExpressAdListener = {
  11847. // /**
  11848. // * 加载失败的回调
  11849. // *
  11850. // * @param code
  11851. // * @param message
  11852. // */
  11853. // onError: (code: number, message: string) => {
  11854. // console.error("加载广告失败,code=" + code + ",message=" + message);
  11855. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  11856. // },
  11857. //
  11858. // /**
  11859. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  11860. // *
  11861. // * @param ads 返回的广告列表
  11862. // */
  11863. //
  11864. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  11865. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  11866. // if (ads && ads.length > 0) {
  11867. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  11868. // ad.setExpressInteractionListener({
  11869. // /**
  11870. // *广告的点击回调
  11871. // * @param type 广告的交互类型
  11872. // */
  11873. // onAdClicked: (type: number) => {
  11874. // console.log("BannerExpressAdPage==onAdClicked......");
  11875. // },
  11876. //
  11877. // /**
  11878. // * 广告的展示回调 每个广告仅回调一次
  11879. // * @param type 广告的交互类型
  11880. // */
  11881. // onAdShow: (type: number) => {
  11882. // console.log("BannerExpressAdPage==onAdShow......");
  11883. // },
  11884. //
  11885. // /**
  11886. // * 模板渲染失败
  11887. // */
  11888. // onRenderFail: (code: number, msg: string) => {
  11889. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  11890. // },
  11891. //
  11892. // /**
  11893. // * 模板渲染成功
  11894. // * @param width 返回view的宽 单位 vp
  11895. // * @param height 返回view的高 单位 vp
  11896. // */
  11897. // onRenderSuccess: (width: number, height: number) => {
  11898. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  11899. // this.bannerAd = ad;
  11900. // this.status = "广告加载完成待展示";
  11901. //
  11902. // this.showBannerAd()
  11903. // }
  11904. // })
  11905. // //渲染广告
  11906. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  11907. // this.setDislikeCallback(ad); //设置dislike
  11908. // ad.render(this.getUIContext())
  11909. // this.status = "广告加载中...";
  11910. // });
  11911. // }
  11912. // }
  11913. // }
  11914. //
  11915. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  11916. // ad.setDislikeCallback({
  11917. // /**
  11918. // * dislike show
  11919. // */
  11920. // onShow: () => {
  11921. // console.log("BannerExpressAdPage==dislike......show");
  11922. // },
  11923. //
  11924. // /**
  11925. // * @param position 选择的位置
  11926. // * @param value 选择的内容
  11927. // * @param enforceRemove 是否强制关闭广告
  11928. // */
  11929. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  11930. // this.isShowAd = false;
  11931. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  11932. // ",enforce=" + enforceRemove);
  11933. // },
  11934. //
  11935. // /**
  11936. // * 点击取消
  11937. // */
  11938. // onCancel: () => {
  11939. // console.log("BannerExpressAdPage==dislike......onCancel");
  11940. // }
  11941. //
  11942. // })
  11943. // }
  11944. /**
  11945. * 加载Banner广告
  11946. */
  11947. loadBannerAd(rit: string) {
  11948. // if (Utility.isNoble()) {
  11949. // return
  11950. // }
  11951. // if (!Utility.isPassInstallTime(2)) {
  11952. // return
  11953. // }
  11954. // this.isShowAd = false;
  11955. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  11956. // this.mAdSlot = new AdSlotBuilder()
  11957. // .setCodeId(rit)
  11958. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  11959. // .setAdCount(1)
  11960. // .setBidAdm(this.mBiddingAdm)
  11961. // .build()
  11962. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  11963. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  11964. // this.status = "广告加载中..."
  11965. }
  11966. /**
  11967. * 展示Banner广告
  11968. */
  11969. // showBannerAd() {
  11970. // if (!this.bannerAd) {
  11971. // return
  11972. // }
  11973. // this.isShowAd = true
  11974. // this.status = "已展示"
  11975. // }
  11976. /**
  11977. * 穿山甲广告代码结束
  11978. */
  11979. /**
  11980. * 处理歌单播放请求
  11981. */
  11982. private handlePlaylistPlayRequest(playlistId: string, playlistName:
  11983. string, songFilePaths: string[], startIndex: number, webDavAuthInfo?: WebDavAuthItem) {
  11984. try {
  11985. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  11986. // 检查是否为WebDAV播放请求
  11987. if (playlistId === 'webdav-playlist') {
  11988. Logger.info(`heanup 检测到WebDAV播放请求,使用事件传递的认证信息`)
  11989. // 如果有WebDAV认证信息,保存到实例变量和全局上下文中
  11990. if (webDavAuthInfo) {
  11991. this.currentWebDavAuthInfo = webDavAuthInfo;
  11992. // 同时保存到全局上下文作为持久化备份(防止实例变量被清空)
  11993. try {
  11994. const globalContext = GlobalContext.getContext();
  11995. globalContext.setObject('webDavAuthInfo', webDavAuthInfo as Object);
  11996. Logger.info(`heanup 已将WebDAV认证信息保存到实例变量和全局上下文,账户ID: ${webDavAuthInfo.accountId}`);
  11997. } catch (error) {
  11998. Logger.error(`heanup 保存到全局上下文失败:`, error.toString());
  11999. }
  12000. } else {
  12001. Logger.warn(`heanup WebDAV播放请求中没有认证信息`);
  12002. }
  12003. // 尝试从全局上下文获取videoItems(如果WebDavMainPage已经保存了的话)
  12004. const globalContext = GlobalContext.getContext();
  12005. const videoItems = globalContext.getObject('videoItems') as VideoItem[];
  12006. const currentPlayIndex = globalContext.getObject('currentPlayIndex') as number;
  12007. Logger.info(`heanup 从GlobalContext获取数据: videoItems长度=${videoItems?.length || 0}, currentPlayIndex=${currentPlayIndex}`);
  12008. if (videoItems && videoItems.length > 0) {
  12009. Logger.info(`heanup 从全局上下文获取到WebDAV歌曲列表,长度:${videoItems.length}`)
  12010. // 验证歌曲数据是否完整
  12011. for (let i = 0; i < Math.min(3, videoItems.length); i++) {
  12012. Logger.info(`heanup 歌曲[${i}]: ${videoItems[i]?.name}, 路径: ${videoItems[i]?.filePath}`)
  12013. }
  12014. this.finishLoadingPlaylist(videoItems, startIndex, playlistName)
  12015. return
  12016. } else {
  12017. Logger.error(`heanup 无法从全局上下文获取WebDAV歌曲数据,尝试使用传入的文件路径创建备用数据`)
  12018. // 备用方案:直接使用传入的文件路径创建VideoItem
  12019. const fallbackVideoItems: VideoItem[] = [];
  12020. for (let i = 0; i < songFilePaths.length; i++) {
  12021. const fileName = songFilePaths[i].split('/').pop() || `WebDAV歌曲${i+1}`;
  12022. const videoItem = new VideoItem(
  12023. fileName.replace(/\.(flac|mp3|wav|m4a)$/i, ''), // name (去掉扩展名)
  12024. '', // id
  12025. songFilePaths[i], // filePath (URL)
  12026. CommonConstants.TYPE_WEBDAV, // type
  12027. 0, // videoSize
  12028. "0", // cTime
  12029. undefined, // pixelMap
  12030. undefined, // size
  12031. undefined, // pixelMapPath
  12032. "WebDAV", // artist
  12033. undefined, // album
  12034. fileName // fileName
  12035. );
  12036. fallbackVideoItems.push(videoItem);
  12037. }
  12038. Logger.info(`heanup 使用备用方案创建了${fallbackVideoItems.length}首WebDAV歌曲`)
  12039. this.finishLoadingPlaylist(fallbackVideoItems, startIndex, playlistName)
  12040. return
  12041. }
  12042. }
  12043. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  12044. const songMap: Map<number, VideoItem> = new Map()
  12045. let completedQueries = 0
  12046. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  12047. // 遍历所有文件路径,使用索引记录位置
  12048. for (let i = 0; i < songFilePaths.length; i++) {
  12049. const filePath = songFilePaths[i]
  12050. const index = i
  12051. Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  12052. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  12053. const queryPromise = this.table.queryVideoByFilePath(filePath)
  12054. Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  12055. queryPromise.then((videoItem) => {
  12056. completedQueries++
  12057. Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  12058. if (videoItem) {
  12059. // 使用索引作为key保存到Map中,保持原始顺序
  12060. songMap.set(index, videoItem)
  12061. Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  12062. } else {
  12063. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  12064. }
  12065. // 检查是否所有歌曲都已加载完成
  12066. if (completedQueries === songFilePaths.length) {
  12067. Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  12068. // 按照索引顺序重建歌曲数组
  12069. const songs: VideoItem[] = []
  12070. for (let j = 0; j < songFilePaths.length; j++) {
  12071. const song = songMap.get(j)
  12072. if (song) {
  12073. songs.push(song)
  12074. Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  12075. }
  12076. }
  12077. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  12078. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12079. }
  12080. }).catch((error: Error) => {
  12081. completedQueries++
  12082. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  12083. // 即使出错也要检查是否完成所有查询
  12084. if (completedQueries === songFilePaths.length) {
  12085. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  12086. // 按照索引顺序重建歌曲数组
  12087. const songs: VideoItem[] = []
  12088. for (let j = 0; j < songFilePaths.length; j++) {
  12089. const song = songMap.get(j)
  12090. if (song) {
  12091. songs.push(song)
  12092. }
  12093. }
  12094. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12095. }
  12096. })
  12097. }
  12098. } catch (error) {
  12099. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  12100. ToastUtil.showToast('播放失败')
  12101. }
  12102. }
  12103. /**
  12104. * 完成歌单加载并开始播放
  12105. */
  12106. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  12107. if (songs.length === 0) {
  12108. Logger.error('heanup 没有找到任何可播放的歌曲')
  12109. ToastUtil.showToast('没有找到可播放的歌曲')
  12110. return
  12111. }
  12112. this.songList = songs
  12113. this.sonDataSource.pushArrayData(songs)
  12114. this.sonDataSource.notifyDataReload()
  12115. this.curIndex = startIndex
  12116. if (songs[startIndex]) {
  12117. // 确保当前播放的歌曲也更新到存储
  12118. AppStorage.setOrCreate('currentSong', songs[startIndex])
  12119. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  12120. this.doPlay(songs[startIndex], startIndex, true)
  12121. }
  12122. PreferencesUtil.putSync('LastMusicList', this.songList)
  12123. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  12124. }
  12125. }
  12126. //视频气泡窗口的布局
  12127. @Builder
  12128. function customPopupBuilder(dataBu: BubbleBean) {
  12129. List() {
  12130. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  12131. ListItem() {
  12132. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12133. Row() {
  12134. Column() {
  12135. Image(dataBu.imageRes[index])
  12136. .height(28)
  12137. .fillColor(dataBu.color)
  12138. .alignSelf(ItemAlign.Center)
  12139. }
  12140. .width(32)
  12141. Text(item)
  12142. .padding({
  12143. top: 10,
  12144. bottom: 10,
  12145. right: 10,
  12146. left: 10
  12147. })
  12148. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  12149. .textAlign(TextAlign.Start)
  12150. .width("100%")
  12151. }
  12152. }
  12153. .backgroundColor($r('app.color.settings_background_main'))
  12154. .margin({ top: 6, bottom: 6 })
  12155. }
  12156. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12157. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  12158. TransitionEffect.scale({ x: 0, y: 0 })))
  12159. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12160. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12161. .onClick(() => {
  12162. dataBu.onItemClick?.(index)
  12163. })
  12164. })
  12165. }
  12166. .scrollBar(BarState.Off)
  12167. .width(120)
  12168. .divider({
  12169. strokeWidth: 1,
  12170. color: "#22FFFFFF"
  12171. })
  12172. }
  12173. // Function to calculate a hash for the file list
  12174. function simpleHash(fileList: string[]): string {
  12175. let hash = 0;
  12176. const str = fileList.join(',');
  12177. for (let i = 0; i < str.length; i++) {
  12178. const char = str.charCodeAt(i);
  12179. hash = (hash << 5) - hash + char;
  12180. hash |= 0; // Convert to 32bit integer
  12181. }
  12182. return hash.toString();
  12183. }
  12184. interface MoreItem {
  12185. id: number;
  12186. image: Resource;
  12187. title: string;
  12188. }
  12189. //视频气泡窗口的布局
  12190. @Builder
  12191. function cutPopupBuilder(dataBu: BubbleBean) {
  12192. Column() {
  12193. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  12194. .padding({
  12195. top: 10,
  12196. bottom: 10,
  12197. right: 10,
  12198. left: 10
  12199. })
  12200. .textAlign(TextAlign.Start)
  12201. .width(160)
  12202. .fontWeight(666)
  12203. .fontSize(16)
  12204. List() {
  12205. ForEach(dataBu.data, (item: string, index: number) => {
  12206. ListItem() {
  12207. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12208. Row() {
  12209. Column() {
  12210. Image($r('app.media.music_group'))
  12211. .height(28)
  12212. .fillColor(dataBu.color)
  12213. .alignSelf(ItemAlign.Center)
  12214. }
  12215. .width(32)
  12216. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  12217. .padding({
  12218. top: 10,
  12219. bottom: 10,
  12220. right: 10,
  12221. left: 10
  12222. })
  12223. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  12224. .fontSize(15)
  12225. }
  12226. }
  12227. .backgroundColor(Color.Transparent)
  12228. .margin({ top: 7, bottom: 7 })
  12229. }
  12230. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12231. .animation({ duration: 500 }),
  12232. TransitionEffect.scale({ x: 0, y: 0 })))
  12233. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12234. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12235. .onClick(() => {
  12236. dataBu.onItemClick?.(index)
  12237. })
  12238. })
  12239. }
  12240. .scrollBar(BarState.Off)
  12241. .width(150)
  12242. .divider({
  12243. strokeWidth: 1,
  12244. color: "#22FFFFFF"
  12245. })
  12246. }
  12247. .height(300)
  12248. .padding({
  12249. bottom: 30
  12250. })
  12251. }
  12252. function getFileDirName(filePath: string,rootPath:string): string{
  12253. if(filePath===rootPath){
  12254. return '首页'
  12255. }
  12256. let result = FileUtil.getFileName(filePath)
  12257. if(StrUtil.isEmpty(result))
  12258. return ''
  12259. if(result.startsWith('.'))
  12260. result = result.replace(/\./g, '')
  12261. return result
  12262. }
  12263. //只扫描当前目录下文件(不扫描子文件夹)的方法
  12264. @Concurrent
  12265. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  12266. const table: MediaTable = new MediaTable(context);
  12267. try {
  12268. // 直接获取当前目录下的文件列表
  12269. const files = FileUtil.listFileSync(dirPath);
  12270. await Promise.all(files.map(async (file) => {
  12271. const fPath = `${dirPath}/${file}`;
  12272. // 跳过目录,只处理文件
  12273. if (FileUtil.isDirectory(fPath)) {
  12274. return;
  12275. }
  12276. // 跳过特定格式文件
  12277. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  12278. return;
  12279. }
  12280. // 检查是否为媒体文件
  12281. if (Utility.isMeidaByExtension(fPath)) {
  12282. let mType = CommonConstants.TYPE_LOCAL;
  12283. if (fPath.includes(lockPath)) {
  12284. mType = CommonConstants.TYPE_LOCK;
  12285. }
  12286. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  12287. context, fPath, mType, true
  12288. );
  12289. table.insert(mediaItem, (id: number) => {
  12290. // 插入回调函数
  12291. }, cover_api);
  12292. }
  12293. }));
  12294. } catch (error) {
  12295. console.error(' 扫描当前目录失败:', error);
  12296. }
  12297. }