LocalMusic.ets 480 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808
  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,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. AppUtil,
  8. ArrayUtil,
  9. Base64Util,
  10. DateUtil,
  11. DeviceUtil,
  12. FileUtil,
  13. GlobalContext,
  14. LogUtil,
  15. MD5,
  16. PreferencesUtil,
  17. RandomUtil,
  18. StrUtil,
  19. ToastUtil
  20. } from '@pura/harmony-utils';
  21. import { imagePathToPixelMap } from '../common/util/CommUtils';
  22. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  23. import { CommonConstants } from '../common/constants/CommonConstants';
  24. import { EventConstants } from '../common/constants/EventConstants';
  25. import Logger from '../common/util/Logger';
  26. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  27. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  28. import { BubbleBean } from '../viewmodel/BubbleBean';
  29. import { PopupPosition, XPopup } from '@chinalike/popup';
  30. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  31. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  32. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  33. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  34. import { Verify } from './Verify';
  35. import { taskpool } from '@kit.ArkTS';
  36. import { RotatingCover } from './RotatingCover';
  37. import { PlayConstants } from '../common/constants/PlayConstants';
  38. import { effectKit } from '@kit.ArkGraphics2D';
  39. import { ColorConversion } from '../common/util/ColorConversion';
  40. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  41. import { AvSessionController } from '../controller/AvSessionController';
  42. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  43. import { FFMpegTags,Utility } from '../common/util/Utility';
  44. import { TagsContentCover } from '../view/TagsContentCover';
  45. import {
  46. // DeviceChangeReason,
  47. IjkMediaPlayer,
  48. InterruptEvent,
  49. InterruptHintType,
  50. LogUtils,
  51. OnBufferingUpdateListener,
  52. OnCompletionListener,
  53. OnErrorListener,
  54. OnInfoListener,
  55. OnPreparedListener,
  56. OnSeekCompleteListener,
  57. OnTimedTextListener,
  58. OnVideoSizeChangedListener
  59. } from '@ohos/ijkplayer';
  60. import { PlayStatus } from '../common/PlayStatus';
  61. import fs from '@ohos.file.fs';
  62. import { image } from '@kit.ImageKit';
  63. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  64. import { UniversalDetector } from '@ohos/juniversalchardet';
  65. import { SettingPage } from '../pages/SettingPage';
  66. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  67. import { CommonConstants2 } from '../common/util/CommonConstants2';
  68. import { hilog } from '@kit.PerformanceAnalysisKit';
  69. import { LazyDataSource } from '../common/util/LazyDataSource';
  70. import MediaTable from '../common/util/MediaTable';
  71. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  72. import ImageUtils from '../common/util/ImageUtils';
  73. import { ringtone } from '@kit.RingtoneKit';
  74. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  75. import { resourceManager } from '@kit.LocalizationKit';
  76. import { deviceInfo } from '@kit.BasicServicesKit';
  77. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  78. import app from '@system.app';
  79. import { TextNodeController } from './PipLyricTextBuilder';
  80. import { IndexerView } from './IndexerView';
  81. import { KeyCode } from '@kit.InputKit';
  82. import { KnockController } from '../controller/KnockController';
  83. import { DeleteComptent } from '../view/DeleteComptent';
  84. import { ABLoopComptent } from '../view/ABLoopComptent';
  85. import { FixMessyView } from '../view/FixMessyView';
  86. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  87. import { CueComptent } from '../view/CueComptent';
  88. import PlaylistTable from '../common/util/PlaylistTable';
  89. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  90. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  91. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  92. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  93. import { WebdavManager, WebDavAuthItem} from '../common/util/WebdavManager';
  94. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  95. const TAG = 'LocalMusic';
  96. /**
  97. * 歌单播放事件数据
  98. */
  99. interface PlaylistEventData {
  100. playlistId: string;
  101. playlistName: string;
  102. songCount: number;
  103. startIndex: number;
  104. songFilePaths: string[];
  105. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  106. }
  107. const DEFAULT_INDEX =
  108. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  109. 'X', 'Y', 'Z']
  110. //排序类型
  111. function getTypeOrder(type: number) {
  112. switch (type) {
  113. case CommonConstants.TYPE_IS_DIR:
  114. return 1; // First
  115. case CommonConstants.TYPE_IS_CSJAD:
  116. return 2; // Middle
  117. case CommonConstants.TYPE_LOCAL:
  118. return 3; // Last
  119. default:
  120. return 4; // Unknown types, if any, go last
  121. }
  122. }
  123. /**
  124. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  125. * @param song 歌曲对象
  126. * @returns Promise<string> 完整的URL
  127. */
  128. /**
  129. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  130. * @param song 歌曲对象
  131. * @returns Promise<string> 完整的URL
  132. */
  133. async function setVideoUrlForSong(song: VideoItem): Promise<string> {
  134. if (song.type === CommonConstants.TYPE_WEBDAV && song.webdav_account_id) {
  135. try {
  136. const fullUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, song.filePath);
  137. if (fullUrl) {
  138. Logger.info(TAG, `WebDAV完整URL构建成功: ${fullUrl}`);
  139. return fullUrl.replace(/ /g, '%20');
  140. } else {
  141. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${song.filePath}`);
  142. return song.filePath.replace(/ /g, '%20');
  143. }
  144. } catch (error) {
  145. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  146. return song.filePath.replace(/ /g, '%20');
  147. }
  148. } else {
  149. // 非WebDAV文件或缺少webdav_account_id,直接使用原始路径
  150. if (song.type === CommonConstants.TYPE_WEBDAV) {
  151. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  152. }
  153. return song.type === CommonConstants.TYPE_WEBDAV ?
  154. song.filePath.replace(/ /g, '%20') :
  155. song.filePath;
  156. }
  157. }
  158. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  159. // 定义接口
  160. interface HiCarAspectRatio {
  161. ratio: number;
  162. name: string;
  163. }
  164. interface GeneratedObjectLiteralInterface_1 {
  165. assetId: string;
  166. title: string;
  167. artist: string;
  168. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  169. mediaUri: string;
  170. // 该字段大写,音频'AUDIO',视频'VIDEO'
  171. mediaType: string;
  172. mediaSize: number;
  173. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  174. startPosition: number;
  175. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  176. duration: number;
  177. albumCoverUri: string;
  178. albumTitle: string;
  179. appName: string;
  180. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  181. drmScheme: string;
  182. }
  183. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  184. const ITEM_HEIGHT: number = 65; // 列表项中高度
  185. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  186. //功能强大的音乐播放器
  187. @Preview
  188. @Component
  189. export struct LocalMusic {
  190. @State isCopyFileToDownLoad: boolean = false
  191. @State offHeight: number = 75
  192. @State currentSongList: Array<VideoItem> = []//当前歌单
  193. @Consume currentSongListName:string //当前歌单名称
  194. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  195. @State isRefreshing: boolean = false;
  196. @State maxRefreshingHeight: number = 100.0;
  197. private contentNode?: ComponentContent<Object> = undefined;
  198. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  199. @State ratioL: number = 1;
  200. @State mediaKuCount: number = 0;
  201. @State albumCount: number = 0;
  202. @State artistCount: number = 0;
  203. @State fastForwardSeconds: string = '10'
  204. @State isShowBackFast: boolean = true//快进快退按钮
  205. @State isCanAuto:boolean = true
  206. @State opacityValueImage: number = 1;
  207. @State tipPopup:boolean = false
  208. @Consume mType: number;
  209. @StorageProp('themeColor') themeColor: string =
  210. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  211. themeMode: number = 0;
  212. @State titleName: string = '首页'
  213. @State textStr: string = ''
  214. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  215. // private download_path: string = '';
  216. @Consume rootPath: string //音频根目录
  217. @Consume currentPath: string
  218. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  219. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  220. @State lockPath: string = ''
  221. @State favPath: string = ''
  222. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  223. @State historyPath: string = ''
  224. @State historyList: Array<VideoItem> = []
  225. @Consume isHistory: boolean
  226. static readonly HISTORY_MUSIC: string = 'music_historyList';
  227. private table: MediaTable = new MediaTable(getContext(this))
  228. private playlistTable: PlaylistTable | null = null
  229. @State allPlaylists: Playlist[] = []
  230. @State isZero: boolean = false
  231. @State fileList: Array<string> = []
  232. @State dirList: Array<VideoItem> = []
  233. @Consume videoLocalList:VideoItem[]
  234. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  235. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  236. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  237. @State artistList: Array<VideoItem> = []; //艺术家文件
  238. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  239. @State albumList: Array<VideoItem> = []; //专辑文件
  240. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  241. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  242. @State imageOpacities: number[] = [];
  243. @Consume isCanBack: boolean
  244. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  245. @State showSingleLyric: boolean = false
  246. @State sortType: number = 4 //默认排序方式
  247. @State isShowSimi: boolean = false //是否显示私密音频
  248. @State isShowFAV: boolean = true //是否显示我的收藏
  249. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  250. @State isShowAllBar: boolean = true //是否显示播放全部条
  251. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  252. @State isShowHistory: boolean = true //是否显示最近播放
  253. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  254. @State isGridMusic: boolean = false //是否网格布局
  255. @State isCircleBtn: boolean = false //是否圆形播放按钮
  256. @State twoFingerType: number = 3 //双支放大缩小的类型
  257. @State isScrollHide: boolean = false //是否滚动隐藏
  258. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  259. @State isStartAutoPlay: boolean = false //启动后自动播放
  260. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  261. @State isShowHeader: boolean = true
  262. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  263. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  264. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  265. @State isSwipe: boolean = false //listItem的左滑开关
  266. @State openSkipSongAnimate: boolean = true//切歌动画效果
  267. @State customizeBgPath: string | undefined = '';
  268. @State isDarkMode: boolean = false
  269. @State lyricTextWeight: number = 400
  270. @State lyricTextWeightPip: number = 400
  271. @State currentSwiperIndex: number = 0
  272. @State blurValue: number = 0 //背景模糊
  273. @State bgBrightness: number = 0 //背景亮度
  274. private listScroller: ListScroller = new ListScroller()
  275. private playListScroller: Scroller = new Scroller()
  276. @State isOneKeyTags:boolean = false
  277. @State isFixMessy:boolean = false
  278. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  279. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  280. @StorageProp('bottomRectHeight') bottomRectHeight: number = 0;
  281. @StorageProp('windowWidth') windowWidth: number = 0;
  282. @StorageProp('windowHeight') windowHeight: number = 0;
  283. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  284. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  285. private UNKONWN:string = '';
  286. private listArea: Area = {
  287. width: 0,
  288. height: 0,
  289. position: {},
  290. globalPosition: {}
  291. }
  292. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  293. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  294. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  295. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  296. //瀑布流的列数横竖屏动态切换
  297. onIsLandscapeChange() {
  298. if(this.isLandscape){
  299. this.columns = 4
  300. }else{
  301. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  302. }
  303. }
  304. onColorModeChange() {
  305. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  306. if (this.isCustomizeBg) {
  307. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  308. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  309. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  310. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  311. this.tabOptions.selectedBackgroundColor = Color.Transparent
  312. } else {
  313. if (!this.isDarkMode) {
  314. this.titleBarModel.setTitleBarBackground(this.themeColor)
  315. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  316. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  317. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  318. this.tabOptions.selectedBackgroundColor = this.themeColor
  319. } else {
  320. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  321. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  322. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  323. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  324. this.tabOptions.selectedBackgroundColor = $r('app.color.silvery')
  325. }
  326. }
  327. }
  328. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  329. onTopBarhange(){
  330. if(this.isShowTitleBar){
  331. console.log('onecold 导航条显示')
  332. this.topBarHeight = 50
  333. this.offHeight = 75
  334. }else{
  335. console.log('onecold 导航条隐藏')
  336. this.topBarHeight = 0
  337. if(this.twoFingerType!=4){
  338. this.offHeight = 30
  339. }
  340. }
  341. }
  342. //点击某个歌单id发生变化的时候回调
  343. onIDChange(){
  344. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  345. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  346. if(this.modeType==4){
  347. this.isShowTitleBar = false
  348. this.titleBarModel.setTitleName(this.currentSongListName)
  349. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  350. //获取缓存
  351. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  352. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  353. if(StrUtil.isNotEmpty(cacheSongs)){
  354. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  355. this.updateListData(this.currentSongList, true)
  356. }
  357. this.doSongListTask()//获取歌单信息
  358. }
  359. }
  360. async doSongListTask() {
  361. // 初始化歌单数据库
  362. const playlistTable = new PlaylistTable(this.context);
  363. // 查询歌单中的所有歌曲
  364. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  365. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  366. if (ArrayUtil.isEmpty(playlistSongs)) {
  367. this.updateListData([], true)
  368. } else {
  369. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  370. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  371. this.updateListData(this.currentSongList, true)
  372. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  373. // 只保存前100条记录到缓存中
  374. let canceList = this.currentSongList.slice(0, 100);
  375. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  376. JSON.stringify(canceList))
  377. } else {
  378. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  379. }
  380. }
  381. this.isRefreshing = false
  382. }
  383. onModeChange() {
  384. this.isFavMusic = false
  385. if (this.modeType === 2 || this.modeType === 3|| this.modeType === 4) {
  386. this.titleBarModel.setRightIcon(null)
  387. } else {
  388. this.titleBarModel.setRightIcon(($r('app.media.add')))
  389. }
  390. LogUtil.info('onecold onModeChange = ' + this.modeType)
  391. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  392. switch (this.modeType) {
  393. case 0:
  394. this.getSortedFiles(this.currentPath)
  395. break
  396. case 1:
  397. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  398. this.updateListData(this.mediaKuList)
  399. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  400. break
  401. case 2:
  402. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  403. this.updateListData(this.artistList)
  404. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  405. break
  406. case 3:
  407. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  408. this.updateListData(this.albumList)
  409. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  410. break
  411. }
  412. }
  413. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  414. // @StorageLink('isPlay') isPlay: boolean = false;
  415. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  416. @StorageLink('songList') songList: Array<VideoItem> = [];
  417. @State translateY: number = 0;
  418. @State isShowSheet: boolean = false;
  419. @State isShowSheetView: boolean = false;
  420. @State isShowTimeCloseView: boolean = false;
  421. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  422. @StorageLink('currIndex') curIndex: number = 0;
  423. @Consume isShowDrawer: boolean;
  424. @Consume offsetX: number;
  425. @State isFac: boolean = false;
  426. @State favList: Array<VideoItem> = []
  427. @Consume isFavMusic: boolean
  428. @State isClickedPLayAll: boolean = false;
  429. private scrollerForlist: ListScroller = new ListScroller();
  430. private knockController: KnockController | undefined = undefined;
  431. imagesF: ImageFrameInfo[] = [
  432. { src: $r("app.media.app_loading0") },
  433. { src: $r("app.media.app_loading1") },
  434. { src: $r("app.media.app_loading2") },
  435. { src: $r("app.media.app_loading3") },
  436. ]
  437. @State animationState: AnimationStatus = AnimationStatus.Initial
  438. // 缓存机制
  439. private cache: Map<string, Array<VideoItem>> = new Map();
  440. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  441. // 持久化缓存
  442. private async saveCacheToStorage() {
  443. const cacheArray = Array.from(this.cache.entries());
  444. const stringCacheArray = Array.from(this.stringCache.entries());
  445. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  446. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  447. }
  448. // 载入缓存
  449. private async loadCacheFromStorage() {
  450. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  451. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  452. if (cacheString) {
  453. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  454. this.cache = new Map(cacheArray);
  455. }
  456. if (stringCacheString) {
  457. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  458. this.stringCache = new Map(stringCacheArray);
  459. }
  460. }
  461. // 查找缓存
  462. private findCache(key: string): Array<VideoItem> | undefined {
  463. return this.cache.get(key);
  464. }
  465. // 查找字符串缓存
  466. private findStringCache(key: string): string | undefined {
  467. return this.stringCache.get(key);
  468. }
  469. // 添加缓存
  470. private addCache(key: string, value: Array<VideoItem>) {
  471. this.cache.set(key, value);
  472. }
  473. // 添加字符串缓存
  474. private addStringCache(key: string, value: string) {
  475. this.stringCache.set(key, value);
  476. }
  477. // 删除缓存
  478. private deleteCache(key: string) {
  479. this.cache.delete(key);
  480. this.saveCacheToStorage()
  481. }
  482. // 删除字符串缓存
  483. private deleteStringCache(key: string) {
  484. this.stringCache.delete(key);
  485. }
  486. // 多选机制
  487. @State selectedFiles: Array<VideoItem> = [];
  488. @State isMultiSelect: boolean = false;
  489. @State isAllSelected: boolean = false;
  490. @State appName: string = ''
  491. @State isHasDir: boolean = false
  492. @State packName: string = ''
  493. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  494. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  495. .setTitleTextStyle(FontStyle.Normal)
  496. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  497. .setLeftIcon($r('app.media.menu'))
  498. .setLeftIconWidth(26)
  499. .setLeftIconHeight(26)
  500. .setTitleName('首页')
  501. .setTitleBarMinHeight(55)
  502. .setTitleFontSize(18)
  503. .setTitleFontColor(Color.White)
  504. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  505. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  506. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  507. .setRightIcon($r('app.media.add'))
  508. .setOnRightClickListener(() => {
  509. this.showSheelDialog()
  510. })
  511. // .setOnTitleClickListener(() => {
  512. // this.showPupDialog()
  513. // })
  514. .setOnLeftClickListener(() => {
  515. this.doSwipBack()
  516. })
  517. doSwipBack() {
  518. this.isZero = false
  519. if (this.modeType !== 0 && this.isCanBack) {
  520. this.onModeChange()
  521. this.isCanBack = false
  522. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  523. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  524. setTimeout(() => {
  525. if (this.modeType == 2) {
  526. if (this.isGridMusic||this.twoFingerType==4) {
  527. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  528. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  529. if(this.twoFingerType==4){
  530. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  531. }else{
  532. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  533. }
  534. } else {
  535. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  536. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  537. }
  538. } else if (this.modeType == 3) {
  539. if (this.isGridMusic||this.twoFingerType==4) {
  540. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  541. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 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('lastListAlBumScrollOffset') ?? 0
  549. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  550. }
  551. }
  552. }, 200)
  553. return
  554. }
  555. if (this.isHistory || this.isFavMusic) {
  556. this.isHistory = false
  557. this.getSortedFiles(this.currentPath)
  558. return
  559. }
  560. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  561. animateTo({ duration: 555 }, () => {
  562. // 动画闭包内控制Image组件的出现和消失
  563. this.isShowDrawer = !this.isShowDrawer
  564. this.offsetX = 0
  565. })
  566. return
  567. }
  568. //返回上一级歌单的滚动位置
  569. setTimeout(() => {
  570. if (this.modeType == 0) {
  571. if (this.isGridMusic||this.twoFingerType==4) {
  572. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  573. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  574. if(this.twoFingerType==4){
  575. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  576. }else{
  577. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  578. }
  579. } else {
  580. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  581. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  582. }
  583. }
  584. }, 300)
  585. this.currentPath = Utility.getParentDirectory(this.currentPath)
  586. Logger.info('this.currentPath2 = ' + this.currentPath)
  587. this.getSortedFiles(this.currentPath)
  588. }
  589. // 组件生命周期
  590. aboutToAppear() {
  591. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  592. this.updateListData(this.videoLocalList)
  593. }
  594. // 初始化 PlaylistTable
  595. this.playlistTable = new PlaylistTable(getContext(this))
  596. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  597. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  598. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  599. this.tipPopup = !this.tipPopup
  600. PreferencesUtil.putSync('isFirstTiped',false)
  601. }
  602. this.initSetting()
  603. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  604. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  605. Utility.getAppName(getContext(this)).then((appName: string) => {
  606. this.appName = appName
  607. })
  608. this.packName = AppUtil.getBundleName()
  609. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  610. this.loadCacheFromStorage(); // 加载文件夹缓存
  611. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  612. this.initLoadCache()
  613. this.mkDownLoadDir()
  614. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  615. // 监听广播事件(打开其他应用处理)
  616. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  617. this.saveVideoDatas([eventData.data?.message], true)
  618. });
  619. //侧滑广播接收时间
  620. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  621. // 监听广播事件(打开其他应用处理)
  622. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  623. animateTo({ duration: 555 }, () => {
  624. this.doSwipBack()
  625. })
  626. });
  627. //ScanFilePage广播接收时间
  628. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  629. // 监听ScanFilePage广播事件(更新数据库)
  630. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  631. this.doUpdateData()
  632. });
  633. // 监听歌单播放请求事件
  634. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  635. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  636. const data = eventData.data as Record<string, Object>
  637. if (!data) {
  638. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  639. return
  640. }
  641. // 检查歌单播放数据结构
  642. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  643. const playlistData: PlaylistEventData = {
  644. playlistId: data.playlistId as string,
  645. playlistName: data.playlistName as string,
  646. songCount: data.songCount as number,
  647. startIndex: data.startIndex as number,
  648. songFilePaths: data.songFilePaths as string[]
  649. }
  650. await this.handlePlaylistPlayRequest(
  651. playlistData.playlistId,
  652. playlistData.playlistName,
  653. playlistData.songFilePaths,
  654. playlistData.startIndex
  655. )
  656. return
  657. }
  658. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  659. });
  660. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  661. // 监听广播事件(通用设置配置更新)
  662. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  663. if(this.modeType ==4){
  664. this.doSongListTask()//获取歌单信息
  665. }
  666. });
  667. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  668. // 监听广播事件(通用设置配置更新)
  669. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  670. this.doChangeSetting()
  671. });
  672. let event: Callback<InterruptEvent> = (event) => {
  673. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  674. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  675. this.savePlaybackPosition()
  676. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  677. this.pause();
  678. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  679. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  680. console.info('onecold startPlayOrResumePlay 514')
  681. this.startPlayOrResumePlay();
  682. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  683. this.stop();
  684. }
  685. }
  686. this.mIjkMediaPlayer.on('audioInterrupt', event);
  687. // 音频设备断连回调处理
  688. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  689. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  690. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  691. // this.pause();
  692. // }
  693. // }
  694. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  695. this.makeWorker()
  696. //折叠屏的屏幕显示模式变化
  697. display.on('foldDisplayModeChange', (data) => {
  698. this.doChangeBarHeight()
  699. });
  700. display.on('foldStatusChange', (data) => {
  701. Logger.info('onecold foldStatusChange ')
  702. });
  703. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  704. // 读取 themeMode 并同步 currentColorMode
  705. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  706. this.applyThemeMode(this.themeMode)
  707. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  708. AppStorage.setOrCreate('themeColor', themeColor);
  709. this.themeColor = themeColor;
  710. this.doChangeSetting()
  711. this.windowClass.on('windowSizeChange', (size) => {
  712. LogUtil.info('onecold windowSizeChange')
  713. this.doChangeBarHeight()
  714. let viewWidth = px2vp(size.width);
  715. let viewHeight = px2vp(size.height);
  716. if(this.isPhoneLan()){
  717. this.is_auto_hide_progress = false
  718. if(this.isHiCar()){
  719. return
  720. }
  721. setTimeout(() => {
  722. this.is_auto_hide_progress = true
  723. }, 6000)
  724. }else{
  725. this.startAutoHide()
  726. }
  727. });
  728. this.eventHub.on('onStateChange', (fg: boolean) => {
  729. if (fg && this.curState === 'STARTED') {
  730. this.stopPip();
  731. }
  732. });
  733. }
  734. //载入媒体库,艺术家,专辑等缓存
  735. initLoadCache(){
  736. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  737. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  738. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  739. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  740. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  741. if(ArrayUtil.isNotEmpty(cachedList)){
  742. this.mediaKuList = cachedList
  743. if(this.modeType==1){
  744. this.updateListData(this.mediaKuList)
  745. }
  746. }
  747. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  748. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  749. if(ArrayUtil.isNotEmpty(artistCachedList)){
  750. this.artistList = artistCachedList
  751. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  752. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  753. this.artistMap = new Map(parsedArray);
  754. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  755. if(this.modeType==2){
  756. this.updateListData(this.artistList)
  757. }
  758. }
  759. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  760. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  761. if(ArrayUtil.isNotEmpty(albumCachedList)){
  762. this.albumList = albumCachedList
  763. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  764. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  765. this.albumMap = new Map(parsedArray);
  766. if(this.modeType==3){
  767. this.updateListData(this.albumList)
  768. }
  769. }
  770. }
  771. startAutoHide() {
  772. if(this.isHiCar()){
  773. return
  774. }
  775. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  776. console.info('onecold startAutoHide')
  777. this.is_auto_hide_progress = false
  778. setTimeout(() => {
  779. this.is_auto_hide_progress = true
  780. }, 6000)
  781. }
  782. }
  783. applyThemeMode(mode: number) {
  784. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  785. if (mode === 1) {
  786. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  787. } else if (mode === 2) {
  788. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  789. }
  790. AppStorage.setOrCreate('currentColorMode', colorMode)
  791. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  792. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  793. AppStorage.setOrCreate('themeMode', mode)
  794. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  795. // 只有强制浅色/深色时才主动设置
  796. const context = getContext(this) as common.UIAbilityContext
  797. context.getApplicationContext().setColorMode(colorMode)
  798. }
  799. initSetting() {
  800. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  801. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  802. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  803. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  804. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  805. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  806. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  807. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  808. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  809. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  810. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  811. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  812. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  813. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  814. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  815. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  816. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  817. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  818. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  819. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  820. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  821. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  822. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  823. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  824. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  825. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  826. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  827. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  828. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  829. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  830. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  831. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  832. if(this.volumeSmall){
  833. this.volume = 0.5
  834. }else{
  835. this.volume = 1
  836. }
  837. //如果是hicar连接状态,这些都是false
  838. if(this.isHiCar()){
  839. this.isShowTitleBar = false//不显示导航栏
  840. this.columns=4
  841. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  842. {
  843. this.isShowHeader = false//二级菜单不显示头部
  844. this.isGridMusic= false//用list不用网格
  845. this.isCoverTopBig = false
  846. }
  847. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  848. }
  849. if (this.isSavePlayMode) {
  850. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  851. }
  852. if (this.isCustomizeBg) {
  853. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  854. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  855. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  856. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  857. } else {
  858. if (!this.isDarkMode) {
  859. this.titleBarModel.setTitleBarBackground(this.themeColor)
  860. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  861. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  862. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  863. } else {
  864. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  865. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  866. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  867. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  868. }
  869. }
  870. }
  871. doChangeSetting() {
  872. this.initSetting()
  873. this.deleteCache(this.currentPath)
  874. if (this.modeType === 0) {
  875. this.getSortedFiles(this.currentPath)
  876. }
  877. }
  878. doChangeBarHeight() {
  879. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  880. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  881. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  882. this.setBarHeightNormal()
  883. }
  884. }
  885. onPageShow() {
  886. this.knockController?.immersiveListening();
  887. app.setImageCacheCount(100);
  888. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  889. app.setImageRawDataCacheSize(104857600);
  890. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  891. }
  892. //开启线程查看各个数据库
  893. makeWorker() {
  894. setTimeout(() => {
  895. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  896. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  897. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  898. // workerInstance.postMessage({
  899. // code: 1,
  900. // data1: this.context,
  901. // data2: this.rootPath,
  902. // data3: this.lockPath,
  903. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  904. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  905. // });
  906. PreferencesUtil.putSync('isFirstApp', false)
  907. } else {
  908. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  909. workerInstance.postMessage({ code: 3, data: this.context });
  910. workerInstance.postMessage({ code: 4, data: this.context });
  911. this.getHistoryList(false)
  912. }
  913. }, 1000)
  914. workerInstance.onmessage = (e: MessageEvents): void => {
  915. switch (e.data.code) {
  916. case 101: //第一次扫描文件夹入库
  917. ToastUtil.showToast('刷新同步数据库成功!')
  918. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  919. this.doUpdateData()
  920. break;
  921. case 102: //查询媒体库列表
  922. this.isRefreshing = false
  923. this.mediaKuList = e.data.data
  924. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  925. Utility.doSortListAscending(this.mediaKuList)
  926. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  927. if (this.modeType === 1) {
  928. this.updateListData(this.mediaKuList)
  929. }
  930. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  931. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  932. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  933. // 只保存前100条记录到缓存中
  934. let truncatedList = this.mediaKuList.slice(0, 100);
  935. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  936. } else {
  937. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  938. }
  939. break;
  940. case 103: //收到查询艺术家列表
  941. this.isRefreshing = false
  942. this.artistMap = e.data.data1;
  943. this.artistList = e.data.data2;
  944. PreferencesUtil.putSync('artistCount', this.artistList.length)
  945. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  946. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  947. // 只保存前100条记录到缓存中
  948. let truncatedList = this.artistList.slice(0, 100);
  949. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  950. } else {
  951. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  952. }
  953. // 处理并缓存前60条艺术家数据
  954. const sortedEntries = Array.from(this.artistMap.entries())
  955. .sort((a, b) => b[1].length - a[1].length)
  956. .slice(0, 60);
  957. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  958. break;
  959. case 104: //收到查询专辑列表
  960. this.isRefreshing = false
  961. this.albumMap = e.data.data1;
  962. this.albumList = e.data.data2
  963. //查询完毕在启动是否自动播放
  964. if (this.isStartAutoPlay&&this.isCanAuto) {
  965. this.isCanAuto = false
  966. console.info('onecold startPlayOrResumePlay 757')
  967. this.startPlayOrResumePlay()
  968. }
  969. PreferencesUtil.putSync('albumCount', this.albumList.length)
  970. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  971. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  972. // 只保存前100条记录到缓存中
  973. let truncatedList = this.albumList.slice(0, 100);
  974. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  975. } else {
  976. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  977. }
  978. const mapArrayAlbum = Array.from(this.albumMap.entries())
  979. .sort((a, b) => b[1].length - a[1].length)
  980. .slice(0, 60);
  981. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  982. break;
  983. }
  984. };
  985. // 在调用terminate后,执行onexit
  986. workerInstance.onexit = (code) => {
  987. console.log("main thread terminate");
  988. }
  989. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  990. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  991. workerInstance.onerror = (err: ErrorEvent) => {
  992. console.log("onerror" + err.message);
  993. }
  994. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  995. //碰一碰分享的监听
  996. this.knockController = KnockController.getInstance(this.context);
  997. this.knockController?.immersiveListening();
  998. }
  999. onPageHide(): void {
  1000. this.knockController?.immersiveDisableListening();
  1001. }
  1002. @State isFirstStartPlay: boolean = false
  1003. //获取download_path
  1004. async mkDownLoadDir() {
  1005. const documentViewPicker = new picker.DocumentViewPicker()
  1006. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1007. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1008. this.currentPath = this.rootPath
  1009. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1010. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1011. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1012. Logger.info('onecold rootPath = ' + this.rootPath)
  1013. Logger.info('onecold lockPath = ' + this.lockPath)
  1014. if (!FileUtil.accessSync(this.lockPath)) {
  1015. FileUtil.mkdirSync(this.lockPath)
  1016. }
  1017. if (!FileUtil.accessSync(this.favPath)) {
  1018. FileUtil.mkdirSync(this.favPath)
  1019. }
  1020. if (!FileUtil.accessSync(this.historyPath)) {
  1021. FileUtil.mkdirSync(this.historyPath)
  1022. }
  1023. this.getSortedFiles(this.rootPath).then(async () => {
  1024. this.isFavMusic = false
  1025. //穿山甲
  1026. // this.loadBannerAd(CSJUtil.getBannerID())
  1027. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1028. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1029. if (ArrayUtil.isEmpty(this.songList)) {
  1030. this.songList = this.getCurFileList()
  1031. } else {
  1032. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1033. }
  1034. if (ArrayUtil.isNotEmpty(this.songList)) {
  1035. this.isFirstStartPlay = true
  1036. this.sonDataSource.pushArrayData(this.songList)
  1037. if (this.currentSong === undefined) {
  1038. this.isFirstStartPlay = false
  1039. this.currentSong = this.songList[0]
  1040. }
  1041. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1042. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  1043. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1044. this.name = this.currentSong.name
  1045. this.cover = this.currentSong.pixelMapPath
  1046. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1047. } else {
  1048. this.name = '空空如也'
  1049. }
  1050. })
  1051. this.getFavList(false)
  1052. }
  1053. getFavList(isFavRefresh: boolean) {
  1054. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1055. this.favList = result
  1056. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1057. this.videoLocalList = this.favList
  1058. this.updateListData(this.videoLocalList)
  1059. }
  1060. })
  1061. }
  1062. getHistoryList(isRefresh: boolean) {
  1063. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1064. this.historyList = result
  1065. // for (let i = 0; i < this.historyList.length; i++) {
  1066. //
  1067. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1068. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1069. // }
  1070. if (isRefresh) {
  1071. this.videoLocalList = this.historyList
  1072. this.updateListData(this.videoLocalList, true)
  1073. }
  1074. })
  1075. }
  1076. // 组件消失生命周期
  1077. aboutToDisappear() {
  1078. console.info('LifeCycleComponent aboutToDisappear');
  1079. this.knockController?.immersiveDisableListening();
  1080. this.curIndex = 0
  1081. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1082. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1083. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1084. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1085. this.mDestroyPage = true;
  1086. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1087. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1088. this.stop();
  1089. }
  1090. this.mIjkMediaPlayer.off('audioInterrupt');
  1091. if (workerInstance) {
  1092. workerInstance.terminate();
  1093. }
  1094. this.stopPip();
  1095. this.destroyPipController()
  1096. }
  1097. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  1098. this.isFavMusic = false
  1099. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1100. if (isWorkerPost) {
  1101. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1102. }
  1103. if (this.modeType !== 0) {
  1104. this.openMusic(isOpen, destPath)
  1105. return
  1106. }
  1107. console.info('onecold getSortedFiles 2')
  1108. this.isCanBack = false
  1109. this.currentPath = curPath
  1110. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1111. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  1112. if (curPath === this.rootPath) {
  1113. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1114. } else {
  1115. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1116. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1117. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  1118. }
  1119. }
  1120. // Get the current file list and calculate its hash
  1121. this.fileList = FileUtil.listFileSync(curPath);
  1122. const currentHash = simpleHash(this.fileList);
  1123. // Check cache
  1124. const cachedValue = this.findCache(curPath);
  1125. Logger.info('onecold cachedValue = ' + cachedValue)
  1126. const cachedHash = this.findStringCache(curPath + '_hash');
  1127. const cachedDirList = this.findCache(curPath + "_dirList");
  1128. if (cachedValue !== undefined) {
  1129. // this.videoLocalList = cachedValue;
  1130. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1131. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1132. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1133. }
  1134. this.updateListData(cachedValue)
  1135. }
  1136. if (cachedDirList !== undefined) {
  1137. this.dirList = cachedDirList
  1138. }
  1139. //通过当前hash值和缓存hash判断list有没有变化
  1140. if (cachedValue && cachedHash === currentHash) {
  1141. return;
  1142. }
  1143. this.fileList = FileUtil.listFileSync(curPath)
  1144. let directories: Array<VideoItem> = [];
  1145. let files: Array<VideoItem> = [];
  1146. for (let i = 0; i < this.fileList.length; i++) {
  1147. console.info(`The name of file: ${this.fileList[i]}`);
  1148. let path = curPath + '/' + this.fileList[i]
  1149. if (FileUtil.isDirectory(path)) {
  1150. let item: VideoItem =
  1151. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1152. '')
  1153. if (this.isShowDir(item.name)) {
  1154. directories.push(item);
  1155. }
  1156. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1157. // Utility.doSortListAscending(directories)
  1158. } else {
  1159. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1160. let item: VideoItem =
  1161. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1162. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1163. files.push(item);
  1164. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1165. // this.doSortListAscending(files)
  1166. }
  1167. }
  1168. }
  1169. }
  1170. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1171. if (this.currentPath !== this.lockPath) {
  1172. files = result;
  1173. }
  1174. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1175. Utility.doSortListAscending(files)
  1176. if (this.currentPath === this.rootPath) {
  1177. this.dirList = directories
  1178. this.addCache(curPath + "_dirList", this.dirList);
  1179. }
  1180. //插入广告先注释掉
  1181. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1182. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1183. // directories.push(adItem)
  1184. // }
  1185. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1186. this.videoLocalList = directories.concat(files);
  1187. this.updateListData(this.videoLocalList)
  1188. if (ArrayUtil.isNotEmpty(files)) {
  1189. if (this.currentPath != this.rootPath) {
  1190. if (files) {
  1191. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1192. }
  1193. }
  1194. // 缓存结果
  1195. this.addCache(curPath, this.videoLocalList);
  1196. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1197. this.addStringCache(curPath + '_hash', currentHash);
  1198. }
  1199. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1200. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1201. //
  1202. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1203. //
  1204. // }
  1205. // this.setButtonStatus()
  1206. this.openMusic(isOpen, destPath)
  1207. });
  1208. }
  1209. //第三方app打开天天静听导入音乐后播放
  1210. openMusic(isOpen?: boolean, destPath?: string){
  1211. if (isOpen&&destPath) {
  1212. if (destPath === undefined) {
  1213. // 处理 destPath 为 undefined 的情况
  1214. return
  1215. }
  1216. if (destPath.endsWith('.lrc')) {
  1217. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1218. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1219. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1220. this.initLyric(lyricPath);
  1221. }
  1222. return
  1223. }
  1224. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  1225. this.doPlay(item2,0,false,true)
  1226. this.isShowPlay = true
  1227. }
  1228. }
  1229. //扫描文件夹入库
  1230. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1231. const files = FileUtil.listFileSync(curPath);
  1232. let mediaItems: VideoItem[] = [];
  1233. Logger.info('onecold scanDirectory start ')
  1234. for (const file of files) {
  1235. const fPath = `${curPath}/${file}`;
  1236. if (fPath === this.lockPath) {
  1237. Logger.info(`Skipping locked path: ${fPath}`);
  1238. continue;
  1239. }
  1240. if (FileUtil.isDirectory(fPath)) {
  1241. // Recursively scan subdirectories
  1242. const subDirItems = await this.scanDirectory(fPath);
  1243. mediaItems = mediaItems.concat(subDirItems);
  1244. } else {
  1245. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1246. // Process media files
  1247. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1248. let mediaItem: VideoItem =
  1249. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1250. mediaItems.push(mediaItem);
  1251. this.table.insert(mediaItem, (id: number) => {
  1252. });
  1253. }
  1254. }
  1255. }
  1256. return mediaItems;
  1257. }
  1258. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1259. animateTo({ duration: 666 }, () => {
  1260. this.opacityItem = 0.5;
  1261. });
  1262. setTimeout(() => {
  1263. this.videoLocalList = mList;
  1264. if (!noSort) {
  1265. if (this.modeType === 0 || this.modeType === 1) {
  1266. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1267. this.doSortType(this.sortType)
  1268. }
  1269. }
  1270. this.dataSource.pushArrayData(this.videoLocalList)
  1271. animateTo({ duration: 666 }, () => {
  1272. this.opacityItem = 1;
  1273. });
  1274. this.setButtonStatus()
  1275. }, 200);
  1276. }
  1277. //排序模式和多选模式
  1278. showPupDialog() {
  1279. if (this.modeType === 2 || this.modeType === 3) {
  1280. this.titleBarModel.setRightIcon(null)
  1281. } else {
  1282. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1283. }
  1284. let dataBean = new BubbleBean()
  1285. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1286. dataBean.color = this.themeColor
  1287. dataBean.modeType = this.modeType
  1288. dataBean.imageRes =
  1289. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1290. $r('app.media.refresh')]
  1291. let pup: XPopup;
  1292. if (this.isDarkMode) {
  1293. pup = XPopup.Builder()
  1294. .setPopupPosition(PopupPosition.BOTTOM)
  1295. .atView('pup_positon_music')
  1296. .setBackgroundColor(Color.Black)
  1297. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1298. .show()
  1299. } else {
  1300. pup = XPopup.Builder()
  1301. .setPopupPosition(PopupPosition.BOTTOM)
  1302. .atView('pup_positon_music')
  1303. .setBackgroundColor(Color.White)
  1304. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1305. .show()
  1306. }
  1307. dataBean.onItemClick = (i) => {
  1308. XPopup.dismissTop()
  1309. switch (i) {
  1310. case 0: //首页
  1311. this.modeType = 0
  1312. this.getSortedFiles(this.currentPath)
  1313. break
  1314. case 1:
  1315. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1316. this.modeType = 1
  1317. this.updateListData(this.mediaKuList)
  1318. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1319. break
  1320. case 2:
  1321. this.modeType = 2
  1322. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1323. this.updateListData(this.artistList)
  1324. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1325. break
  1326. case 3:
  1327. this.modeType = 3
  1328. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1329. this.updateListData(this.albumList)
  1330. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1331. break
  1332. case 4: //同步数据
  1333. // this.asyncCurrentPathData()
  1334. break
  1335. }
  1336. }
  1337. }
  1338. getCurFileList(): Array<VideoItem> {
  1339. if(this.isSearchMode){
  1340. return this.filteredList
  1341. }
  1342. let files: Array<VideoItem> = [];
  1343. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1344. for (let i = 0; i < this.videoLocalList.length; i++) {
  1345. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1346. files.push(this.videoLocalList[i]);
  1347. }
  1348. }
  1349. }
  1350. return files
  1351. }
  1352. setButtonStatus() {
  1353. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1354. this.isZero = false
  1355. } else {
  1356. this.isZero = true
  1357. }
  1358. if (this.currentPath !== this.rootPath &&
  1359. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1360. this.isHasDir = true //不为空,说明有子文件夹
  1361. } else {
  1362. this.isHasDir = false
  1363. }
  1364. }
  1365. showRankDialog() {
  1366. if ((this.modeType === 2&&!this.isCanBack) || (this.modeType === 3&&!this.isCanBack)) {
  1367. //动作面板
  1368. DialogHelper.showBottomSheetDialog({
  1369. title: "请选择排序模式",
  1370. maskColor: Color.Transparent,
  1371. // sheets: ["按名称升序", "按名称降序"],
  1372. sheets: [
  1373. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1374. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1375. { value: '按数量升序', fontColor: $r('app.color.text_color') },
  1376. { value: '按数量降序', fontColor: $r('app.color.text_color') },
  1377. ],
  1378. backgroundColor: $r('app.color.bg_card'),
  1379. height: '45%',
  1380. transition: AnimationHelper.transitionInDown(555),
  1381. onAction: (index) => {
  1382. switch (index) {
  1383. case 0:
  1384. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1385. break;
  1386. case 1:
  1387. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1388. break;
  1389. case 2:
  1390. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1391. // 1. Sort by type first
  1392. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1393. if (typeOrder !== 0) {
  1394. return typeOrder;
  1395. }
  1396. // 2. Then sort by artist count (numeric comparison)
  1397. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1398. if(this.modeType === 2){
  1399. sortMap = this.artistMap
  1400. }else{
  1401. sortMap = this.albumMap
  1402. }
  1403. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1404. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1405. return aArtistCount - bArtistCount;
  1406. });
  1407. break;
  1408. case 3:
  1409. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1410. // 1. Sort by type first
  1411. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1412. if (typeOrder !== 0) {
  1413. return typeOrder;
  1414. }
  1415. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1416. if(this.modeType === 2){
  1417. sortMap = this.artistMap
  1418. }else{
  1419. sortMap = this.albumMap
  1420. }
  1421. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1422. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1423. return bArtistCount - aArtistCount;
  1424. });
  1425. break;
  1426. }
  1427. this.updateListData(this.videoLocalList)
  1428. }
  1429. })
  1430. return
  1431. }
  1432. //动作面板
  1433. DialogHelper.showBottomSheetDialog({
  1434. title: "请选择排序模式",
  1435. maskColor: Color.Transparent,
  1436. height: '75%',
  1437. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1438. sheets: [
  1439. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1440. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1441. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1442. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1443. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1444. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1445. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1446. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1447. ],
  1448. backgroundColor: $r('app.color.bg_card'),
  1449. transition: AnimationHelper.transitionInDown(555),
  1450. onAction: (index) => {
  1451. this.doSortType(index)
  1452. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1453. this.updateListData(this.videoLocalList, true)
  1454. }
  1455. })
  1456. }
  1457. doSortType(index: number) {
  1458. switch (index) {
  1459. case 0:
  1460. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1461. // 类型排序优先级
  1462. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1463. if (typeOrder !== 0) {
  1464. return typeOrder;
  1465. }
  1466. // 处理艺术家可能为undefined的字符串比较
  1467. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1468. const artistB = b.artist?.trim() || '';
  1469. return artistA.localeCompare(artistB);
  1470. });
  1471. break;
  1472. case 1:
  1473. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1474. // 类型排序优先级
  1475. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1476. if (typeOrder !== 0) {
  1477. return typeOrder;
  1478. }
  1479. // 处理艺术家可能为undefined的字符串比较
  1480. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1481. const artistB = b.artist?.trim() || '';
  1482. return artistB.localeCompare(artistA);
  1483. });
  1484. break;
  1485. case 2:
  1486. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1487. // 类型排序优先级
  1488. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1489. if (typeOrder !== 0) {
  1490. return typeOrder;
  1491. }
  1492. // 处理专辑可能为undefined的字符串比较
  1493. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1494. const albumB = b.album?.trim() || '';
  1495. return albumA.localeCompare(albumB);
  1496. });
  1497. break;
  1498. case 3:
  1499. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1500. // 类型排序优先级
  1501. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1502. if (typeOrder !== 0) {
  1503. return typeOrder;
  1504. }
  1505. // 处理专辑可能为undefined的字符串比较
  1506. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1507. const albumB = b.album?.trim() || '';
  1508. return albumB.localeCompare(albumA);
  1509. });
  1510. break;
  1511. case 4:
  1512. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1513. break;
  1514. case 5:
  1515. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1516. break;
  1517. case 6:
  1518. this.videoLocalList.sort((a, b) => {
  1519. // First, sort by type
  1520. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1521. if (typeOrder !== 0) {
  1522. return typeOrder;
  1523. }
  1524. // If types are the same, sort by cTime in ascending order
  1525. return a.cTime.localeCompare(b.cTime);
  1526. });
  1527. break;
  1528. case 7:
  1529. this.videoLocalList.sort((a, b) => {
  1530. // First, sort by type
  1531. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1532. if (typeOrder !== 0) {
  1533. return typeOrder;
  1534. }
  1535. // If types are the same, sort by cTime in descending order
  1536. return b.cTime.localeCompare(a.cTime);
  1537. });
  1538. break;
  1539. }
  1540. }
  1541. showSheelDialog() {
  1542. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1543. // this.showTips()
  1544. // return
  1545. // }
  1546. this.showAddDialog()
  1547. }
  1548. showAddDialog() {
  1549. if (this.modeType === 2 || this.modeType === 3) {
  1550. return
  1551. }
  1552. DialogHelper.showActionSheetDialog({
  1553. title: "请选择添加方式(建议歌词文件一起导入)",
  1554. sheets: [
  1555. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  1556. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1557. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1558. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1559. ],
  1560. maskColor: Color.Transparent,
  1561. backgroundColor: $r('app.color.bg_card'),
  1562. transition: AnimationHelper.transitionInDown(555),
  1563. onAction: (index) => {
  1564. switch (index) {
  1565. case 0:
  1566. if (this.modeType === 0) {
  1567. this.showMkDialog()
  1568. } else {
  1569. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  1570. }
  1571. break;
  1572. case 1:
  1573. this.callFilePickerSelectFile()
  1574. break;
  1575. case 2:
  1576. this.showTips()
  1577. break;
  1578. case 3:
  1579. this.goSelectMusic()
  1580. break;
  1581. }
  1582. }
  1583. })
  1584. }
  1585. //拉起音频
  1586. goSelectMusic() {
  1587. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1588. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1589. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1590. ) {
  1591. ToastUtil.showToast('暂时不支持该设备')
  1592. return
  1593. }
  1594. try {
  1595. let documentSelectOptions = new picker.DocumentSelectOptions();
  1596. documentSelectOptions.authMode = true
  1597. documentSelectOptions.multiAuthMode = true
  1598. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1599. let documentPicker = new picker.DocumentViewPicker(this.context);
  1600. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1601. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1602. this.saveVideoDatas(documentSelectResult)
  1603. }
  1604. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1605. JSON.stringify(documentSelectResult));
  1606. }).catch((err: BusinessError) => {
  1607. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1608. });
  1609. } catch (error) {
  1610. let err: BusinessError = error as BusinessError;
  1611. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1612. }
  1613. }
  1614. async showTips() {
  1615. DialogHelper.showTipsDialog({
  1616. title: '使用提示:自动导入教程',
  1617. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1618. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1619. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1620. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1621. onAction: (action) => {
  1622. if (action == DialogAction.TWO) {
  1623. PreferencesUtil.putSync('isFirstMusic', false)
  1624. router.pushUrl({
  1625. url: 'pages/ScanFilePage'
  1626. });
  1627. }
  1628. }
  1629. })
  1630. }
  1631. showMkDialog() {
  1632. DialogHelper.showTextInputDialog({
  1633. title: '新建歌单',
  1634. maskColor: Color.Transparent,
  1635. text: '',
  1636. transition: AnimationHelper.transitionInDown(666),
  1637. onChange: (text) => {
  1638. console.error("onChange: " + text);
  1639. },
  1640. onAction: (action, dialogId, content) => {
  1641. // ToastUtil.showToast('content = ' +content)
  1642. if (action == DialogAction.TWO) {
  1643. const newName = content
  1644. const newPath = this.currentPath + '/' + newName
  1645. FileUtil.mkdir(newPath, true).then(() => {
  1646. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1647. this.getSortedFiles(this.currentPath)
  1648. }).catch((error: BusinessError) => {
  1649. console.error(error.message);
  1650. });
  1651. }
  1652. }
  1653. })
  1654. }
  1655. @State progress: number = 0;
  1656. async saveVideoDatas(uris:string[],isOpen?:boolean){
  1657. if (ArrayUtil.isEmpty(uris)) {
  1658. return;
  1659. }
  1660. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  1661. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath){
  1662. this.saveVideoDatasToDownLoad(uris,isOpen)
  1663. return
  1664. }
  1665. // 初始化进度条
  1666. this.progress = 0;
  1667. DialogHelper.showLoadingProgress({
  1668. progress: this.progress,
  1669. backCancel: false,
  1670. autoCancel: false,
  1671. loadColor: $r('app.color.title_bar_bg'),
  1672. fontColor: $r('app.color.title_bar_bg')
  1673. });
  1674. // 计算处理总数用于进度计算
  1675. const totalItems = uris.length;
  1676. let processedItems = 0;
  1677. for (let i = 0; i < uris.length; i++) {
  1678. let filePath = uris[i];
  1679. try {
  1680. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  1681. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1682. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  1683. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1684. console.info('onecold saveVideoDatas filePath = ' + filePath)
  1685. if (!filePath.includes(this.rootPath)) {
  1686. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  1687. mediaItem.parentPath = this.currentPath;
  1688. }
  1689. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  1690. this.table.insert(mediaItem, (id: number) => {
  1691. // 插入完成回调
  1692. });
  1693. }
  1694. }
  1695. // 更新进度
  1696. processedItems++;
  1697. this.progress = Math.floor((processedItems / totalItems) * 100);
  1698. DialogHelper.updateLoading(' 正在处理', this.progress);
  1699. } catch (error) {
  1700. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1701. // 即使出错也更新进度
  1702. processedItems++;
  1703. this.progress = Math.floor((processedItems / totalItems) * 100);
  1704. DialogHelper.updateLoading(' 正在处理', this.progress);
  1705. }
  1706. }
  1707. // 关闭进度条
  1708. DialogHelper.closeLoading();
  1709. this.isZero = false
  1710. // 删除目标路径缓存
  1711. setTimeout(() => {
  1712. this.cache.delete(this.currentPath);
  1713. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  1714. this.setButtonStatus()
  1715. }, 500);
  1716. }
  1717. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  1718. if (ArrayUtil.isEmpty(uris)) {
  1719. return;
  1720. }
  1721. let newUris: string[] = [];
  1722. this.progress = 0
  1723. DialogHelper.showLoadingProgress({
  1724. progress: this.progress,
  1725. backCancel: false,
  1726. autoCancel: false,
  1727. loadColor: this.themeColor,
  1728. fontColor: this.themeColor
  1729. });
  1730. // 计算所有文件的总大小
  1731. let totalSize = 0;
  1732. for (let uri of uris) {
  1733. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1734. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1735. await fileIo.close(sourceFile.fd);
  1736. }
  1737. let totalRead = 0;
  1738. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1739. Logger.info(TAG, 'destPath uri: ' + destPath);
  1740. for (let i = 0; i < uris.length; i++) {
  1741. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1742. Logger.info(TAG, 'filePath uri: ' + filePath);
  1743. newUris.push(filePath);
  1744. try {
  1745. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1746. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1747. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1748. const buffer = new ArrayBuffer(buffSize);
  1749. let len = await fileIo.read(sourceFile.fd, buffer);
  1750. while (len > 0) {
  1751. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1752. totalRead += len;
  1753. // 计算总进度
  1754. this.progress = Math.floor((totalRead / totalSize) * 100);
  1755. DialogHelper.updateLoading('正在导入', this.progress);
  1756. len = await fileIo.read(sourceFile.fd, buffer);
  1757. }
  1758. await fileIo.close(sourceFile.fd);
  1759. await fileIo.close(destFile.fd);
  1760. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1761. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1762. let mediaItem: VideoItem =
  1763. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1764. this.table.insert(mediaItem, (id: number) => {
  1765. // 删除目标路径缓存
  1766. this.cache.delete(this.currentPath);
  1767. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1768. });
  1769. }
  1770. }
  1771. } catch (error) {
  1772. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1773. }
  1774. }
  1775. DialogHelper.closeLoading()
  1776. this.isZero = false
  1777. // setTimeout(() => {
  1778. // // 删除目标路径缓存
  1779. // this.cache.delete(this.currentPath);
  1780. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1781. // }, 500);
  1782. Logger.info(TAG, 'scan select video result:' + newUris)
  1783. }
  1784. //拉起音频
  1785. // goSelectMusic(){
  1786. //
  1787. // try {
  1788. // let audioSelectOptions = new picker.AudioSelectOptions();
  1789. // let audioPicker = new picker.AudioViewPicker(this.context);
  1790. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1791. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1792. // this.saveVideoDatas(audioSelectResult)
  1793. // }
  1794. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1795. // }).catch((err: BusinessError) => {
  1796. //
  1797. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1798. // });
  1799. // } catch (error) {
  1800. // let err: BusinessError = error as BusinessError;
  1801. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1802. // }
  1803. //
  1804. //
  1805. //
  1806. // }
  1807. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1808. if (!item) {
  1809. return undefined;
  1810. }
  1811. try {
  1812. let selectUris: Array<string> = [];
  1813. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1814. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1815. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1816. photoSelectOptions.maxSelectNumber = 1;
  1817. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1818. selectUris = photoSelectResult.photoUris;
  1819. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1820. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1821. console.info('file fd: ' + file.fd);
  1822. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1823. let imagePath = this.context.filesDir + FileUtil.separator + name
  1824. imagePath = fileUri.getUriFromPath(imagePath)
  1825. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1826. fileIo.copyFileSync(file.fd, file2.fd)
  1827. fileIo.closeSync(file);
  1828. fileIo.closeSync(file2);
  1829. if (item.filePath == this.currentSong?.filePath) {
  1830. this.cover = imagePath
  1831. }
  1832. if (item) {
  1833. item.pixelMapPath = imagePath
  1834. }
  1835. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1836. if (success) {
  1837. this.doUpdateData()
  1838. console.log("onecold 更新音乐封面成功,数据库已同步");
  1839. } else {
  1840. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1841. }
  1842. });
  1843. LogUtil.debug("onecold this.cover =" + this.cover)
  1844. return FileUtil.getFilePath(imagePath); // Return the image path here
  1845. } catch (err) {
  1846. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1847. return undefined;
  1848. }
  1849. }
  1850. // 拉起picker选择文件管理器
  1851. async callFilePickerSelectFile(): Promise<void> {
  1852. try {
  1853. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1854. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1855. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1856. } else {
  1857. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1858. }
  1859. let documentPicker = new picker.DocumentViewPicker();
  1860. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1861. Logger.info(TAG,
  1862. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1863. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1864. this.saveVideoDatas(DocumentSelectResult)
  1865. }
  1866. }).catch((err: BusinessError) => {
  1867. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1868. });
  1869. } catch (err) {
  1870. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1871. }
  1872. }
  1873. //重命名的对话框
  1874. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1875. DialogHelper.showTextInputDialog({
  1876. title: '重命名',
  1877. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1878. maskColor: Color.Transparent,
  1879. backgroundColor: Color.Grey,
  1880. transition: AnimationHelper.transitionInDown(666),
  1881. onChange: (text) => {
  1882. console.error("onChange: " + text);
  1883. },
  1884. onAction: (action, dialogId, content) => {
  1885. // ToastUtil.showToast('content = ' +content)
  1886. if (action == DialogAction.TWO) {
  1887. const newName = content
  1888. const newPath = this.currentPath + '/' + newName
  1889. console.log("onecold item = " + item.type);
  1890. this.doReName(index, newName, filePath, newPath, item)
  1891. }
  1892. }
  1893. })
  1894. }
  1895. //剪切 移动到另个文件夹的对话框
  1896. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1897. Logger.info('onecold showCutDialog')
  1898. let mList: Array<string> = []
  1899. let rPath = this.rootPath
  1900. if (isCurrent) {
  1901. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1902. rPath = this.currentPath
  1903. } else {
  1904. mList = Utility.getNameList(this.dirList);
  1905. rPath = this.rootPath
  1906. }
  1907. let dataBean = new BubbleBean()
  1908. dataBean.data = mList
  1909. dataBean.color = this.themeColor
  1910. dataBean.onItemClick = (i) => {
  1911. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1912. Logger.info('newPath = ' + newPath)
  1913. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1914. ToastUtil.showToast('移动成功')
  1915. this.table.deleteData(item, () => {
  1916. });
  1917. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1918. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1919. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1920. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1921. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1922. this.table.insert(newItem, (id: number) => {
  1923. //加入数据库
  1924. });
  1925. }
  1926. this.cache.delete(this.currentPath); // 删除原路径缓存
  1927. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1928. this.getSortedFiles(this.currentPath, true)
  1929. }).catch((error: BusinessError) => {
  1930. console.error(error.message);
  1931. });
  1932. XPopup.dismissTop()
  1933. }
  1934. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1935. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1936. popupPosition = PopupPosition.TOP
  1937. }
  1938. if (index <= 3) {
  1939. popupPosition = PopupPosition.BOTTOM
  1940. }
  1941. let pup: XPopup
  1942. if (this.isDarkMode) {
  1943. pup = XPopup.Builder()
  1944. .setPopupPosition(popupPosition)
  1945. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1946. .setBackgroundColor(Color.Black)
  1947. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1948. .show()
  1949. } else {
  1950. pup = XPopup.Builder()
  1951. .setPopupPosition(popupPosition)
  1952. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1953. .setBackgroundColor(Color.White)
  1954. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1955. .show()
  1956. }
  1957. }
  1958. //复制 到另个文件夹的对话框
  1959. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1960. Logger.info('onecoldv showCopyDialog')
  1961. let mList: Array<string> = []
  1962. let rPath = this.rootPath
  1963. if (isCurrent) {
  1964. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1965. rPath = this.currentPath
  1966. } else {
  1967. mList = Utility.getNameList(this.dirList);
  1968. rPath = this.rootPath
  1969. }
  1970. let dataBean = new BubbleBean()
  1971. dataBean.data = mList
  1972. dataBean.isCopy = true
  1973. dataBean.color = this.themeColor
  1974. dataBean.onItemClick = (i) => {
  1975. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1976. Logger.info('newPath = ' + newPath)
  1977. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1978. ToastUtil.showToast('复制成功')
  1979. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1980. this.getSortedFiles(this.currentPath)
  1981. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1982. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1983. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1984. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1985. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1986. this.table.insert(newItem, (id: number) => {
  1987. //加入数据库
  1988. });
  1989. }
  1990. }).catch((error: BusinessError) => {
  1991. console.error(error.message);
  1992. });
  1993. XPopup.dismissTop()
  1994. }
  1995. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1996. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1997. popupPosition = PopupPosition.TOP
  1998. }
  1999. if (index <= 3) {
  2000. popupPosition = PopupPosition.BOTTOM
  2001. }
  2002. let pup: XPopup
  2003. if (this.isDarkMode) {
  2004. pup = XPopup.Builder()
  2005. .setPopupPosition(popupPosition)
  2006. .atView(id)
  2007. .setMaxHeight('60%')
  2008. .setBackgroundColor(Color.Black)
  2009. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2010. .show();
  2011. } else {
  2012. pup = XPopup.Builder()
  2013. .setPopupPosition(popupPosition)
  2014. .atView(id)
  2015. .setMaxHeight('60%')
  2016. .setBackgroundColor(Color.White)
  2017. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2018. .show();
  2019. }
  2020. }
  2021. //重命名索引index的视频
  2022. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2023. FileUtil.rename(oldPath, newPath).then(async () => {
  2024. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2025. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2026. //如果是文件夹先删除源数据,再添加新数据
  2027. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2028. if (success) {
  2029. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2030. } else {
  2031. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2032. }
  2033. });
  2034. this.scanDirectory(newPath)
  2035. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2036. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2037. if (success) {
  2038. console.log(" onecold 重命名成功,数据库已同步");
  2039. } else {
  2040. console.error(" onecold 重命名数据库失败原因: " + error);
  2041. }
  2042. });
  2043. }
  2044. let mediaItem: VideoItem =
  2045. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2046. this.videoLocalList[index] = mediaItem;
  2047. }
  2048. this.cache.delete(this.currentPath)
  2049. this.getSortedFiles(this.currentPath, true)
  2050. }).catch((error: BusinessError) => {
  2051. console.error(error.message);
  2052. });
  2053. }
  2054. build() {
  2055. Scroll() {
  2056. Column() {
  2057. if (!this.isShowCoverHeader()) {
  2058. Column() {
  2059. Line().width('100%').height('100%')
  2060. }
  2061. .height(this.topRectHeight)
  2062. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  2063. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  2064. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2065. TitleBar({ model: $titleBarModel })
  2066. .id('pup_positon_music')
  2067. }
  2068. Stack() {
  2069. Column() {
  2070. XComponent({
  2071. id: 'xcomponentId',
  2072. type: 'surface',
  2073. libraryname: 'ijkplayer_napi',
  2074. controller: this.xcomponentController
  2075. })
  2076. .onLoad((event?: object) => {
  2077. if (!!event) {
  2078. this.initDelayPlay(event);
  2079. }
  2080. })
  2081. .onKeyEvent((event?: KeyEvent) => {
  2082. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2083. if (!event || event.type !== KeyType.Down) {
  2084. return;
  2085. }
  2086. //空格键 Space key controls pause/play
  2087. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  2088. console.info('onecold playOrPause 1999')
  2089. this.playOrPause()
  2090. }
  2091. // Right-click to fast forward
  2092. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2093. this.sessionFastForwardCallback(15);
  2094. }
  2095. // Left-click to rewind
  2096. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2097. this.sessionRewindCallback(15);
  2098. }
  2099. })
  2100. .onDestroy(() => {
  2101. })
  2102. .width('100%')// .width(this.videoWidth)
  2103. .aspectRatio(this.videoAspectRatio)
  2104. }
  2105. .aspectRatio(this.videoAspectRatio)
  2106. .justifyContent(FlexAlign.Center)
  2107. .backgroundColor(Color.Transparent)
  2108. .visibility(Visibility.Hidden)
  2109. .height(CommonConstants.FULL_PERCENT)
  2110. .width(CommonConstants.FULL_PERCENT)
  2111. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2112. height:this.isLandscape?'80%': '43%',
  2113. dragBar: true,
  2114. showClose: true,
  2115. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2116. blurStyle:BlurStyle.Thin,
  2117. backgroundColor:Color.Transparent,
  2118. title: { title: 'AB循环' }
  2119. })
  2120. Stack() {
  2121. Row() {
  2122. Blank()
  2123. .layoutWeight(1)
  2124. IndexerView(
  2125. {
  2126. indexArray: DEFAULT_INDEX,
  2127. selectedIndex: this.selectedIndex,
  2128. textSize: 12,
  2129. selectedColor: "#ff419ee5",
  2130. normalColor: "#ffa0a0a0",
  2131. floatSelectedTextColor: "#ffffff",
  2132. floatSelectedViewColor: "#ff419ee5",
  2133. onIndexChanged: (index) => {
  2134. this.listScroller.scrollToIndex(index)
  2135. }
  2136. })
  2137. .width(24)
  2138. .height("50%")
  2139. }.visibility(Visibility.None)
  2140. Column() {
  2141. if (!this.isShowCoverHeader()) {
  2142. this.tabTitle()
  2143. }
  2144. if(this.twoFingerType==4){
  2145. this.getWaterView()
  2146. }else{
  2147. if(this.isGridMusic){
  2148. this.getGridView()
  2149. }else {
  2150. this.getList()
  2151. }
  2152. }
  2153. if (this.modeType ==0||this.modeType==4) {
  2154. Column() {
  2155. emptyView(this.themeColor)
  2156. }
  2157. .position({ top:this.isShowCoverHeader() ? 260 : 180 })
  2158. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2159. .animation({ duration: 500 }),
  2160. TransitionEffect.scale({ x: 0, y: 0 })))
  2161. .justifyContent(FlexAlign.Center)
  2162. .opacity(this.isZero ? 1 : 0)
  2163. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2164. ? Visibility.Visible : Visibility.None)
  2165. .animation({
  2166. duration: 500,
  2167. curve: 'ease-in-out' // 可选动画曲线
  2168. })
  2169. .width('100%')
  2170. }
  2171. }
  2172. .layoutWeight(1)
  2173. .height('100%')
  2174. }
  2175. .layoutWeight(1)
  2176. .height('100%')
  2177. Row() {
  2178. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2179. .width(50)
  2180. .height(50)
  2181. .fontSize(13)
  2182. .margin({ top: 10, bottom: 10, right: 6 })
  2183. .backgroundColor(this.themeColor)
  2184. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2185. .onClick(() => {
  2186. if (this.isAllSelected) {
  2187. // 全不选
  2188. this.selectedFiles = [];
  2189. } else {
  2190. // 全选
  2191. this.selectedFiles = [...this.getCurFileList()];
  2192. }
  2193. this.isAllSelected = !this.isAllSelected;
  2194. })
  2195. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2196. .width(90)
  2197. .height(50)
  2198. .fontSize(13)
  2199. .margin({ top: 10, bottom: 10, right: 6 })
  2200. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2201. .backgroundColor(this.themeColor)
  2202. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2203. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2204. })
  2205. .onClick(() => {
  2206. this.isOneKeyTags = !this.isOneKeyTags
  2207. })
  2208. Button('乱码修复', { type: ButtonType.Capsule, stateEffect: true })
  2209. .width(90)
  2210. .height(50)
  2211. .fontSize(13)
  2212. .margin({ top: 10, bottom: 10, right: 6 })
  2213. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2214. .backgroundColor(this.themeColor)
  2215. .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2216. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2217. })
  2218. .onClick(() => {
  2219. this.isFixMessy = !this.isFixMessy
  2220. })
  2221. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2222. // .width('35%')
  2223. // .height(60)
  2224. // .id('music_cut')
  2225. // .margin({ top: 10, bottom: 10, right: 6 })
  2226. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2227. // .backgroundColor(this.themeColor)
  2228. // .onClick(() => {
  2229. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2230. // })
  2231. //
  2232. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2233. // .width('35%')
  2234. // .height(60)
  2235. // .id('music_cut_current')
  2236. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2237. // .margin({ top: 10, bottom: 10, right: 6 })
  2238. // .backgroundColor(this.themeColor)
  2239. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2240. // .onClick(() => {
  2241. //
  2242. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2243. // })
  2244. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2245. // .width('35%')
  2246. // .height(60)
  2247. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2248. // .margin({ top: 10, bottom: 10, right: 6 })
  2249. // .backgroundColor(this.themeColor)
  2250. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2251. // .onClick(() => {
  2252. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2253. // })
  2254. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2255. .width(50)
  2256. .height(50)
  2257. .fontSize(13)
  2258. .margin({ top: 10, bottom: 10, right: 6 })
  2259. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2260. .backgroundColor(this.themeColor)
  2261. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2262. .onClick(() => {
  2263. this.showWarnIsDelete()
  2264. })
  2265. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2266. .width(50)
  2267. .height(50)
  2268. .fontSize(13)
  2269. .margin({ top: 10, bottom: 10, right: 6 })
  2270. .backgroundColor(this.themeColor)
  2271. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2272. .onClick(() => {
  2273. this.selectedFiles = [];
  2274. this.isAllSelected = false
  2275. this.isMultiSelect = false
  2276. })
  2277. }
  2278. .width('100%')
  2279. .justifyContent(FlexAlign.Center)
  2280. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2281. .opacity(this.isMultiSelect ? 1 : 0)
  2282. .animation({
  2283. duration: 666,
  2284. curve: 'ease-in-out' // 可选动画曲线
  2285. })
  2286. .position(this.isShowCoverHeader() ? { bottom: 78 }
  2287. : { bottom: this.isPhoneLan() ? 130 : 170 }) // 将 Row 固定在底部
  2288. }
  2289. .width('100%')
  2290. .height('100%')
  2291. .alignContent(Alignment.Top)
  2292. Column() {
  2293. this.PlayController()
  2294. }
  2295. .hitTestBehavior(HitTestMode.Transparent)
  2296. .position({ bottom: 0 }) // 将 Row 固定在底部
  2297. .opacity(this.barBottomOpacity)
  2298. }
  2299. .width('100%')
  2300. .height('100%')
  2301. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2302. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2303. .backgroundImagePosition(Alignment.Center)
  2304. .backdropBlur(this.blurValue)
  2305. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2306. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2307. }
  2308. }
  2309. @Builder
  2310. TagsContentCoverBuilder() {
  2311. Scroll() {
  2312. Column() {
  2313. TagsContentCover(
  2314. {
  2315. selectedFiles:this.selectedFiles,
  2316. isOneKeyTags:this.isOneKeyTags,
  2317. onTagsResult:(result: boolean)=>{
  2318. this.isMultiSelect = false
  2319. if(result){//如果嵌入成功,更新数据
  2320. this.doUpdateData()
  2321. }
  2322. }
  2323. }
  2324. )
  2325. }
  2326. }
  2327. .width('100%')
  2328. .height('100%')
  2329. }
  2330. @Builder
  2331. FixMessyViewBuilder() {
  2332. Scroll() {
  2333. Column() {
  2334. FixMessyView(
  2335. {
  2336. selectedFiles:this.selectedFiles,
  2337. isFixMessy:this.isFixMessy,
  2338. onFixResult:(result: boolean)=>{
  2339. this.isMultiSelect = false
  2340. if(result){//如果嵌入成功,更新数据
  2341. this.doUpdateData()
  2342. }
  2343. }
  2344. }
  2345. )
  2346. }
  2347. }
  2348. .width('100%')
  2349. .height('100%')
  2350. }
  2351. asyncCurrentPathData() {
  2352. if (this.modeType == 0) {
  2353. workerInstance.postMessage({
  2354. code: 1,
  2355. data1: this.context,
  2356. data2: this.currentPath,
  2357. data3: this.lockPath,
  2358. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2359. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  2360. });
  2361. }
  2362. }
  2363. // 处理文件选择的函数
  2364. handleFileSelection(item: VideoItem, checked: boolean) {
  2365. if (checked) {
  2366. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2367. this.selectedFiles.push(item);
  2368. }
  2369. } else {
  2370. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2371. if (index > -1) {
  2372. this.selectedFiles.splice(index, 1);
  2373. }
  2374. }
  2375. }
  2376. private deleteComponentId: number = 0
  2377. //多选删除文件
  2378. showWarnIsDelete(){
  2379. this.getUIContext().getPromptAction().openCustomDialog({
  2380. builder: () => {
  2381. this.deleteComptentBuilder()
  2382. },
  2383. isModal:true,
  2384. showInSubWindow:false,
  2385. maskColor: Color.Transparent,
  2386. dialogTransition: // 设置弹窗内容显示的过渡效果
  2387. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  2388. .animation({ duration: 600, curve: Curve.Smooth }),
  2389. maskTransition: // 设置蒙层显示的过渡效果
  2390. TransitionEffect.opacity(0)
  2391. .animation({ duration: 600, curve: Curve.Smooth })
  2392. }).then((dialogId: number) => {
  2393. this.deleteComponentId = dialogId
  2394. })
  2395. .catch((error: BusinessError) => {
  2396. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  2397. })
  2398. }
  2399. @Builder
  2400. deleteComptentBuilder(){
  2401. DeleteComptent({
  2402. selectedFiles:this.selectedFiles,
  2403. onCancel:()=>{
  2404. this.isMultiSelect = false
  2405. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2406. },
  2407. onDeleteResult:(result: boolean)=>{
  2408. this.isMultiSelect = false
  2409. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2410. if(result){//如果删除成功,更新数据
  2411. this.selectedFiles = [];
  2412. this.isAllSelected = false
  2413. this.cache.delete(this.currentPath);
  2414. this.getSortedFiles(this.currentPath, true);
  2415. }
  2416. }
  2417. })
  2418. }
  2419. //多选移动文件
  2420. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2421. Logger.info('onecold showCutDialogForMultipleFiles')
  2422. let mList: Array<string> = []
  2423. let rPath = this.rootPath
  2424. if (isCurrent) {
  2425. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2426. rPath = this.currentPath
  2427. } else {
  2428. mList = Utility.getNameList(this.dirList);
  2429. rPath = this.rootPath
  2430. }
  2431. let dataBean = new BubbleBean();
  2432. dataBean.data = mList;
  2433. dataBean.color = this.themeColor
  2434. dataBean.onItemClick = (i) => {
  2435. const newDirPath = rPath + '/' + mList[i];
  2436. // Logger.info('newDirPath = ' + newDirPath)
  2437. this.selectedFiles.forEach((item) => {
  2438. const newPath = newDirPath + '/' + item.fileName;
  2439. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2440. ToastUtil.showToast('移动成功');
  2441. this.table.deleteData(item, () => {
  2442. this.cache.delete(this.currentPath); // 删除原路径缓存
  2443. this.cache.delete(newDirPath); // 删除目标路径缓存
  2444. this.getSortedFiles(this.currentPath, true);
  2445. });
  2446. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2447. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2448. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2449. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2450. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2451. this.table.insert(newItem, (id: number) => {
  2452. //加入数据库
  2453. });
  2454. }
  2455. }).catch((error: Error) => {
  2456. console.error(error.message);
  2457. });
  2458. });
  2459. this.isMultiSelect = false
  2460. this.selectedFiles = [];
  2461. this.isAllSelected = false
  2462. XPopup.dismissTop();
  2463. };
  2464. let pup: XPopup
  2465. if (this.isDarkMode) {
  2466. pup = XPopup.Builder()
  2467. .setPopupPosition(PopupPosition.TOP)
  2468. .atView(viewId)
  2469. .setBackgroundColor(Color.Black)
  2470. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2471. .show();
  2472. } else {
  2473. pup = XPopup.Builder()
  2474. .setPopupPosition(PopupPosition.TOP)
  2475. .atView(viewId)
  2476. .setBackgroundColor(Color.White)
  2477. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2478. .show();
  2479. }
  2480. }
  2481. /**
  2482. * 加载所有歌单
  2483. */
  2484. async loadAllPlaylists() {
  2485. try {
  2486. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  2487. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  2488. } catch (error) {
  2489. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  2490. }
  2491. }
  2492. /**
  2493. * 显示添加到歌单对话框
  2494. */
  2495. async showAddToPlaylistDialog(item: VideoItem) {
  2496. // 加载最新的歌单列表
  2497. await this.loadAllPlaylists()
  2498. showAddToPlaylistDialog(
  2499. item,
  2500. this.allPlaylists,
  2501. async (playlistId: string) => {
  2502. // 添加歌曲到歌单
  2503. const success = await this.playlistTable?.addSongToPlaylist(playlistId, item.filePath)
  2504. if (success) {
  2505. ToastUtil.showToast('已添加到歌单')
  2506. // 重新加载歌单列表
  2507. await this.loadAllPlaylists()
  2508. } else {
  2509. ToastUtil.showToast('歌曲已在该歌单中')
  2510. }
  2511. },
  2512. () => {
  2513. LogUtil.info('取消添加到歌单')
  2514. },
  2515. () => {
  2516. // 创建新歌单
  2517. showCreatePlaylistDialog(
  2518. async (name: string, description: string, coverPath?: string) => {
  2519. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  2520. if (success) {
  2521. ToastUtil.showToast('歌单创建成功')
  2522. // 重新加载歌单列表并打开添加对话框
  2523. await this.loadAllPlaylists()
  2524. await this.showAddToPlaylistDialog(item)
  2525. } else {
  2526. ToastUtil.showToast('歌单创建失败')
  2527. }
  2528. },
  2529. () => {
  2530. // 取消创建歌单
  2531. }
  2532. )
  2533. }
  2534. )
  2535. }
  2536. doFav(item: VideoItem) {
  2537. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2538. let isFav = 0
  2539. if (Utility.getIsFav(this.favList, item)) {
  2540. isFav = 0
  2541. } else {
  2542. isFav = 1
  2543. }
  2544. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2545. if (result) {
  2546. if (isFav === 1) {
  2547. ToastUtil.showToast('收藏成功');
  2548. } else {
  2549. ToastUtil.showToast('取消收藏成功');
  2550. }
  2551. this.deleteCache(this.currentPath)
  2552. this.getFavList(false)
  2553. if (this.modeType === 0 && !this.isFavMusic) {
  2554. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2555. this.getSortedFiles(this.currentPath)
  2556. }
  2557. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2558. workerInstance.postMessage({ code: 3, data: this.context });
  2559. workerInstance.postMessage({ code: 4, data: this.context });
  2560. }
  2561. })
  2562. }
  2563. //多选复制文件
  2564. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2565. console.log('onecold showCopyDialogForMultipleFiles');
  2566. let mList: Array<string> = []
  2567. let rPath = this.rootPath
  2568. if (isCurrent) {
  2569. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2570. rPath = this.currentPath
  2571. } else {
  2572. mList = Utility.getNameList(this.dirList);
  2573. rPath = this.rootPath
  2574. }
  2575. let dataBean = new BubbleBean();
  2576. dataBean.data = mList;
  2577. dataBean.isCopy = true
  2578. dataBean.color = this.themeColor
  2579. dataBean.onItemClick = (i) => {
  2580. const newDirPath = rPath + '/' + mList[i];
  2581. // Logger.info('newDirPath = ' + newDirPath)
  2582. this.selectedFiles.forEach((item) => {
  2583. const newPath = newDirPath + '/' + item.fileName;
  2584. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2585. ToastUtil.showToast('复制成功');
  2586. this.cache.delete(newDirPath); // 删除目标路径缓存
  2587. this.getSortedFiles(this.currentPath);
  2588. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2589. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2590. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2591. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2592. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2593. this.table.insert(newItem, (id: number) => {
  2594. //加入数据库
  2595. });
  2596. }
  2597. }).catch((error: Error) => {
  2598. console.error(error.message);
  2599. });
  2600. });
  2601. this.isMultiSelect = false
  2602. this.selectedFiles = [];
  2603. this.isAllSelected = false
  2604. XPopup.dismissTop();
  2605. };
  2606. let pup: XPopup
  2607. if (this.isDarkMode) {
  2608. pup = XPopup.Builder()
  2609. .setPopupPosition(PopupPosition.TOP)
  2610. .atView(viewId)
  2611. .setBackgroundColor(Color.Black)
  2612. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2613. .show();
  2614. } else {
  2615. pup = XPopup.Builder()
  2616. .setPopupPosition(PopupPosition.TOP)
  2617. .atView(viewId)
  2618. .setBackgroundColor(Color.White)
  2619. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2620. .show();
  2621. }
  2622. }
  2623. @Builder
  2624. private DirItem(item: VideoItem, index?: number) {
  2625. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2626. Row() {
  2627. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2628. $r('app.media.music_group'))
  2629. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2630. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2631. .fillColor(this.themeColor)// .fontSize(33)
  2632. .alt($r('app.media.music_group'))
  2633. .borderRadius('100%')
  2634. .clip(true)
  2635. .margin({ left: 20, top: 8, bottom: 8 })
  2636. Column() {
  2637. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2638. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2639. .maxLines(1)// .width('88%')
  2640. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2641. .animation({
  2642. duration: 555,
  2643. curve: 'ease-in-out',
  2644. })
  2645. .transition({
  2646. type: TransitionType.Insert,
  2647. opacity: 0,
  2648. translate: { x: 160 }
  2649. })
  2650. .margin({ left: 10, right: 20 })
  2651. .fontColor($r('app.color.text_color'))
  2652. Row() {
  2653. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2654. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2655. .padding({ top: 8 })
  2656. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2657. .fontColor($r('app.color.text_color'))
  2658. .margin({ left: 10 })
  2659. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2660. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2661. .padding({ top: 8 })
  2662. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2663. .fontColor($r('app.color.text_color'))
  2664. .margin({ left: 10 })
  2665. Blank()
  2666. }
  2667. }
  2668. .height('100%')
  2669. .layoutWeight(1)
  2670. .justifyContent(FlexAlign.Center)
  2671. .alignItems(HorizontalAlign.Start)
  2672. Blank()
  2673. Image($r('app.media.arrow_right'))
  2674. .height(25)
  2675. .margin({ right: 10 })
  2676. .alignSelf(ItemAlign.Center)
  2677. .id(item.filePath)
  2678. }
  2679. }
  2680. .backgroundColor(Color.Transparent)
  2681. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2682. .width('100%')
  2683. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2684. .opacity(this.opacityItem) // 绑定透明度
  2685. }
  2686. isShowDir(dirName: string) {
  2687. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2688. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2689. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2690. if (dirName === undefined) {
  2691. return true
  2692. }
  2693. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2694. return this.isShowSimi
  2695. }
  2696. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2697. return this.isShowFAV
  2698. }
  2699. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2700. return this.isShowHistory
  2701. }
  2702. return true
  2703. }
  2704. @State opacityItem: number = 1; // 控制透明度的状态变量
  2705. @Builder
  2706. private MusicItem(item: VideoItem, index?: number) {
  2707. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2708. Row() {
  2709. Stack() {
  2710. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2711. .fillColor(this.themeColor)
  2712. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2713. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2714. .alt($r('app.media.music_red'))
  2715. .borderRadius('100%')
  2716. .clip(true)
  2717. .draggable(false)
  2718. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2719. .autoResize(true) // 重采样,可减少内存占用
  2720. .opacity(this.opacityItem)// 绑定透明度
  2721. .margin({ left: 20 })
  2722. .gesture(LongPressGesture()
  2723. .onAction(async () => {
  2724. //如果是专辑和艺术家的首页,不能长按
  2725. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2726. return
  2727. //如果是我的收藏 最近播放等也不能长按
  2728. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2729. item.name === LocalMusic.STR_HISTORY_MUSIC
  2730. )
  2731. return
  2732. this.longItemFilePath = item.filePath
  2733. this.tempLyricContent = await this.getLyricContent(item)
  2734. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2735. })
  2736. .onActionEnd((event: GestureEvent) => {
  2737. }))
  2738. .onClick(()=>{
  2739. this.doPlay(item,index)
  2740. this.isShowPlay = true
  2741. })
  2742. }
  2743. Column() {
  2744. Column() {
  2745. Text(this.isShowFileName?item.fileName :item.name)
  2746. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2747. .maxLines(1)
  2748. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2749. .animation({
  2750. duration: 555,
  2751. curve: 'Linear',
  2752. })
  2753. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2754. $r('app.color.text_color'))
  2755. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2756. .padding({right:25})
  2757. .bindPopup(this.longItemFilePath === item.filePath, {
  2758. builder: this.MenuBuilder(item,index,item.filePath),
  2759. placement: Placement.Top,
  2760. // autoCancel: true,
  2761. mask: {color:'#33000000'},
  2762. // popupColor: Color.Yellow,
  2763. enableArrow: false,//是否显示箭头
  2764. showInSubWindow: false,
  2765. onStateChange: (e) => {
  2766. if (!e.isVisible) {
  2767. this.longItemFilePath = ''
  2768. this.tempLyricContent = ''
  2769. }
  2770. }
  2771. })
  2772. .gesture(LongPressGesture()
  2773. .onAction(async () => {
  2774. //如果是专辑和艺术家的首页,不能长按
  2775. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2776. return
  2777. //如果是我的收藏 最近播放等也不能长按
  2778. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2779. item.name === LocalMusic.STR_HISTORY_MUSIC
  2780. )
  2781. return
  2782. this.longItemFilePath = item.filePath
  2783. this.tempLyricContent = await this.getLyricContent(item)
  2784. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2785. })
  2786. .onActionEnd((event: GestureEvent) => {
  2787. })
  2788. )
  2789. Row() {
  2790. Column(){
  2791. Text(item.md5Str?.includes('Lossless')?
  2792. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2793. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2794. .padding({ top: 3,right:6,left:6,bottom:3 })
  2795. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2796. $r('app.color.text_color'))
  2797. .fontWeight(500)
  2798. .borderRadius(12)
  2799. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2800. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2801. .backgroundColor('#FFC107')
  2802. }
  2803. .padding({ top: 8 })
  2804. Text(StrUtil.isEmpty(item.artist) ? item.duration
  2805. :this.twoFingerType==2? item.artist +' ' + item.duration
  2806. : item.artist + ' ' + item?.duration)
  2807. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2808. .padding({ top: 8 ,right:25})
  2809. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  2810. .maxLines(1)
  2811. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2812. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2813. Color.Gray)
  2814. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2815. Blank()
  2816. Text(this.isShowFileName?item.duration:item.size)
  2817. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2818. .padding({ top: 8 })
  2819. .maxLines(1)
  2820. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  2821. ? Visibility.Visible : Visibility.None)
  2822. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2823. Color.Gray)
  2824. .margin({ left: 10 })
  2825. }
  2826. .gesture(LongPressGesture()
  2827. .onAction(async () => {
  2828. //如果是专辑和艺术家的首页,不能长按
  2829. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2830. return
  2831. //如果是我的收藏 最近播放等也不能长按
  2832. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2833. item.name === LocalMusic.STR_HISTORY_MUSIC
  2834. )
  2835. return
  2836. this.longItemFilePath = item.filePath
  2837. this.tempLyricContent = await this.getLyricContent(item)
  2838. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2839. })
  2840. .onActionEnd((event: GestureEvent) => {
  2841. })
  2842. )
  2843. }
  2844. .height('100%')
  2845. .width('100%')
  2846. .margin({ right: 10 })
  2847. .justifyContent(FlexAlign.Center)
  2848. .alignItems(HorizontalAlign.Start)
  2849. }
  2850. .height('100%')
  2851. .margin({ left: 5 })
  2852. .layoutWeight(1)
  2853. Column() {
  2854. Checkbox({ name: 'checkbox' + index })
  2855. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2856. .selectedColor(this.themeColor)
  2857. .shape(CheckBoxShape.CIRCLE)
  2858. .opacity(this.isMultiSelect ? 1 : 0)
  2859. .animation({
  2860. duration: 666,
  2861. curve: 'Smooth' // 可选动画曲线
  2862. })
  2863. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2864. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2865. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  2866. .width(22)
  2867. .height(22)
  2868. ImageAnimator()
  2869. .images(this.imagesF)// 动画数组
  2870. .duration(1000)// 持续
  2871. .state(this.animationState)// 动画状态
  2872. .fillMode(FillMode.Forwards)
  2873. .width(18)
  2874. .margin({ right: 20, top: 8, bottom: 8 })
  2875. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2876. Visibility.None)
  2877. .height(18)
  2878. .iterations(-1) // 播放次数
  2879. }
  2880. }
  2881. }
  2882. .backgroundColor(Color.Transparent)
  2883. .width('100%')
  2884. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2885. }
  2886. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2887. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  2888. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  2889. direction: Direction.Ltr,
  2890. buttonPadding:{top:12,bottom:12},
  2891. backgroundColor: Color.Transparent,
  2892. fontSize:14,
  2893. selectedFontSize:15,
  2894. selectedFontColor:Color.White,
  2895. selectedBackgroundColor: this.themeColor,
  2896. localizedTextPadding: {
  2897. end: LengthMetrics.vp(20),
  2898. start: LengthMetrics.vp(20)
  2899. }
  2900. })
  2901. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  2902. //当胶囊按钮的选择发生变化时调用此函数
  2903. capsuleSelectedIndexesChanged() {
  2904. this.modeType = this.tabSelectedIndexes[0]
  2905. }
  2906. @Builder
  2907. tabTitle() {
  2908. Column({ space: 2 }) {
  2909. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  2910. Line()
  2911. .width('100%')
  2912. .height(1)
  2913. .backgroundColor($r('app.color.index_background'))
  2914. .opacity(this.barOpacity)
  2915. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2916. }
  2917. .width('100%')
  2918. .height(this.topBarHeight)
  2919. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2920. }
  2921. // @Builder
  2922. // tabTitle() {
  2923. // Column() {
  2924. // // 使用 Stack 布局来实现绝对定位效果
  2925. // Stack() {
  2926. // // 背景动画容器
  2927. // Row() {
  2928. // ForEach(this.tabs, (i: string, index) => {
  2929. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2930. // Flex()
  2931. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2932. // .borderRadius(20)
  2933. // .padding(10)
  2934. // .margin(6)
  2935. // .width('100%')
  2936. // .height('100%')
  2937. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2938. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2939. // .opacity(this.modeType === index ? 1 : 0)
  2940. // .animation({
  2941. // duration: 666,
  2942. // playMode: PlayMode.Normal,
  2943. // curve: 'ease-in-out'
  2944. // });
  2945. // }
  2946. // .layoutWeight(1)
  2947. // .margin({
  2948. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2949. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2950. // });
  2951. // });
  2952. // }
  2953. // .width('100%')
  2954. // .height(50);
  2955. //
  2956. // // 导航栏容器
  2957. // Row() {
  2958. // ForEach(this.tabs, (item: string, index) => {
  2959. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2960. // Text(item)
  2961. // .fontSize(16)
  2962. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2963. // .padding(15)
  2964. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2965. // .onClick(() => {
  2966. // this.modeType = index;
  2967. // // this.onModeChange();
  2968. // });
  2969. // }
  2970. // .layoutWeight(1)
  2971. // .stateStyles({
  2972. // pressed: { opacity: 0.6 } // 按压反馈
  2973. // });
  2974. // });
  2975. // }
  2976. // .width('100%')
  2977. // .height(this.topBarHeight)
  2978. // .opacity(this.barOpacity)
  2979. // .backgroundColor(Color.Transparent);
  2980. //
  2981. // }
  2982. // .width('100%')
  2983. // .height(this.topBarHeight)
  2984. // .opacity(this.barOpacity)
  2985. //
  2986. // Line()
  2987. // .width('100%')
  2988. // .height(1)
  2989. // .backgroundColor($r('app.color.index_background'))
  2990. // .opacity(this.barOpacity)
  2991. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2992. // }
  2993. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2994. // }
  2995. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2996. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2997. isShowCoverHeader() {
  2998. if (!this.isShowHeader) {
  2999. return false
  3000. }
  3001. if (this.modeType == 0) {
  3002. if (this.isHistory || this.isFavMusic) {
  3003. return true
  3004. }
  3005. if (this.currentPath != this.rootPath) {
  3006. return true
  3007. }
  3008. }
  3009. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  3010. }
  3011. @Builder
  3012. coverHeader() {
  3013. if (this.isShowCoverHeader()) {
  3014. Column() {
  3015. Stack() {
  3016. // 居中标题
  3017. Text('')
  3018. .fontSize(18)
  3019. .fontColor(Color.White)
  3020. .align(Alignment.Center)
  3021. // 左右按钮
  3022. Row() {
  3023. Image($r('app.media.left_back_white'))
  3024. .width(28)
  3025. .height(28)
  3026. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3027. .margin({ left: 12, right: 8 })
  3028. .onClick(() => {
  3029. animateTo({ duration: 555 }, () => {
  3030. this.doSwipBack()
  3031. })
  3032. })
  3033. Blank().flexGrow(1)
  3034. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  3035. Image($r('app.media.add'))
  3036. .width(25)
  3037. .height(25)
  3038. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3039. .margin({ left: 8, right: 15 })
  3040. .onClick(() => {
  3041. this.showAddDialog()
  3042. })
  3043. }
  3044. }
  3045. .height(48)
  3046. .width('100%')
  3047. .alignItems(VerticalAlign.Center)
  3048. }
  3049. .height(48)
  3050. .width('100%')
  3051. Row() {
  3052. Column() {
  3053. Image(this.currentTitleCover)
  3054. .height(100)
  3055. .width(100)
  3056. .alt(this.imageLabel)
  3057. .borderRadius(8)
  3058. .clickEffect({ level: ClickEffectLevel.HEAVY })
  3059. }
  3060. .alignItems(HorizontalAlign.Start)
  3061. .margin({ left: 30, top: 3, bottom: 15 })
  3062. Column() {
  3063. Column() {
  3064. Text(this.currentTitleName)
  3065. .fontSize(16)
  3066. .maxLines(1)
  3067. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3068. .fontWeight(FontWeight.Bold)
  3069. .fontColor($r('app.color.text_color'))
  3070. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3071. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3072. Text(`艺术家:${this.videoLocalList[0].artist}`)
  3073. .fontSize(14)
  3074. .padding({ top: 8 })
  3075. .maxLines(1)
  3076. .fontWeight(FontWeight.Bold)
  3077. .fontColor($r('app.color.text_color'))
  3078. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3079. if(this.videoLocalList[0].genre){
  3080. Text(`风格:${this.videoLocalList[0].genre}`)
  3081. .fontSize(14)
  3082. .padding({ top: 8 })
  3083. .maxLines(1)
  3084. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  3085. this.videoLocalList[0].genre.includes(this.UNKONWN)
  3086. ?Visibility.None:Visibility.Visible)
  3087. .fontWeight(FontWeight.Bold)
  3088. .fontColor($r('app.color.text_color'))
  3089. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3090. }
  3091. if(this.videoLocalList[0].year){
  3092. Text(`发行时间:${this.videoLocalList[0].year}`)
  3093. .fontSize(14)
  3094. .padding({ top: 8 })
  3095. .maxLines(1)
  3096. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  3097. this.videoLocalList[0].year.includes(this.UNKONWN)
  3098. ?Visibility.None:Visibility.Visible)
  3099. .fontWeight(FontWeight.Bold)
  3100. .fontColor($r('app.color.text_color'))
  3101. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3102. }
  3103. }
  3104. if(this.modeType != 3){
  3105. Row() {
  3106. Text(`共${this.videoLocalList.length}首歌`)
  3107. .fontSize(13)
  3108. .fontWeight(FontWeight.Bold)
  3109. .padding({ top: 8 })
  3110. .fontColor($r('app.color.text_color'))
  3111. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3112. Blank()
  3113. }
  3114. }
  3115. }
  3116. .height('100%')
  3117. .width('100%')
  3118. .justifyContent(FlexAlign.Center)
  3119. .alignItems(HorizontalAlign.Start)
  3120. }
  3121. .height('100%')
  3122. .layoutWeight(1)
  3123. .margin({ left: 20 })
  3124. }
  3125. this.listViewTitle()
  3126. }
  3127. .backgroundImage(this.getCoverTitleBg())
  3128. .height(250)
  3129. .width('100%')
  3130. .backgroundImageSize({ height: '100%', width: '100%' })
  3131. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  3132. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  3133. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  3134. .justifyContent(FlexAlign.SpaceBetween)
  3135. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  3136. TransitionEffect.scale({ x: 0, y: 0 })))
  3137. } else {
  3138. this.listViewTitle()
  3139. }
  3140. }
  3141. getCoverTitleBg(): ResourceStr | image.PixelMap {
  3142. if (this.isCustomizeBg) {
  3143. return ('rgba(255,255,255,0.2)')
  3144. }
  3145. if (this.isDarkMode) {
  3146. return $r('app.color.user_center_card_background')
  3147. }
  3148. return this.currentTitleCover
  3149. }
  3150. @Builder
  3151. listViewTitle() {
  3152. Column() {
  3153. Row({ space: 8 }) {
  3154. Row({ space: 8 }) {
  3155. Image($r("app.media.hm_playlist"))
  3156. .width(25)
  3157. .margin({ left: 8 })
  3158. .fillColor(this.themeColor)
  3159. Text(this.artistList.length ==100 ? `共找到${this.artistCount}位艺术家`
  3160. :`共找到${this.artistList.length}位艺术家`)
  3161. .fontColor($r('app.color.text_color'))
  3162. .fontSize(14)
  3163. .opacity(this.opacityItem)
  3164. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3165. Text(this.albumList.length ==100 ? `共找到${this.albumCount+''}张专辑`
  3166. :`共找到${this.albumList.length}张专辑`)
  3167. .fontColor($r('app.color.text_color'))
  3168. .opacity(this.opacityItem)
  3169. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3170. .fontSize(14)
  3171. }
  3172. .layoutWeight(1)
  3173. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3174. Row() {
  3175. TextInput({
  3176. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  3177. text: this.searchText
  3178. })
  3179. .height(35)
  3180. .onChange((value: string) => {
  3181. this.onSearchInput(value);
  3182. })
  3183. .layoutWeight(1)
  3184. Text(`取消`)
  3185. .margin({ left: 10, right: 10 })
  3186. .fontColor($r('app.color.text_color'))
  3187. .fontSize(16)
  3188. .onClick(() => {
  3189. this.isSearchMode = false
  3190. this.searchText = ''
  3191. if (this.modeType === 2) {
  3192. this.updateListData(this.artistList)
  3193. } else {
  3194. this.updateListData(this.albumList)
  3195. }
  3196. })
  3197. }
  3198. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3199. .animation({
  3200. duration: 666,
  3201. curve: 'ease-in-out' // 可选动画曲线
  3202. })
  3203. Blank()
  3204. Image($r("app.media.search"))
  3205. .width(25)
  3206. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3207. .animation({
  3208. duration: 666,
  3209. curve: 'ease-in-out' // 可选动画曲线
  3210. })// .opacity(this.opacityItem)
  3211. .fillColor(this.themeColor)
  3212. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3213. .onClick(() => {
  3214. this.isSearchMode = true
  3215. })
  3216. Image($r("app.media.top_rank"))
  3217. .width(25)// .opacity(this.opacityItem)
  3218. .fillColor(this.themeColor)
  3219. .animation({
  3220. duration: 666,
  3221. curve: 'ease-in-out' // 可选动画曲线
  3222. })
  3223. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3224. .onClick(() => {
  3225. this.showRankDialog()
  3226. })
  3227. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3228. .width(25)
  3229. .animation({
  3230. duration: 666,
  3231. curve: 'ease-in-out' // 可选动画曲线
  3232. })
  3233. .fillColor(this.themeColor)
  3234. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3235. .onClick(() => {
  3236. this.isGridMusic = !this.isGridMusic
  3237. })
  3238. }
  3239. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  3240. Visibility.None)
  3241. .width('100%')
  3242. .padding(10)
  3243. .height(50)
  3244. .border({
  3245. width: { bottom: 1 },
  3246. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3247. })
  3248. Row({ space: 8 }) {
  3249. Row({ space: 8 }) {
  3250. Image($r("app.media.hm_play"))
  3251. .width(25)
  3252. .margin({ left: 8 })
  3253. .fillColor(this.themeColor)
  3254. Text(`播放全部`)
  3255. .fontColor($r('app.color.text_color'))
  3256. .fontSize(14)
  3257. .animation({
  3258. duration: 666,
  3259. curve: 'ease-in-out' // 可选动画曲线
  3260. })
  3261. if(Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length>0){
  3262. Text(this.modeType==1&&Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length==100?
  3263. `(${this.mediaKuCount}首)`
  3264. :`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  3265. .fontColor($r('app.color.text_color'))
  3266. .fontSize(14)
  3267. .opacity(this.opacityItem)
  3268. .animation({
  3269. duration: 666,
  3270. curve: 'ease-in-out' // 可选动画曲线
  3271. })
  3272. }
  3273. }
  3274. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3275. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3276. .animation({
  3277. duration: 666,
  3278. curve: 'ease-in-out' // 可选动画曲线
  3279. })
  3280. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  3281. .onTouch((event: TouchEvent) => {
  3282. if (event.type === TouchType.Down) {
  3283. this.isClickedPLayAll = true;
  3284. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  3285. this.isClickedPLayAll = false;
  3286. }
  3287. })
  3288. .onClick(() => {
  3289. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  3290. if (this.modeType === 0) {
  3291. const playList = this.getCurFileList();
  3292. const item = Utility.getPlayItem(playList, this.playType);
  3293. if (item) { // 显式检查undefined
  3294. this.doPlay(item);
  3295. }
  3296. } else {
  3297. const item = Utility.getPlayItem(this.mediaKuList, this.playType);
  3298. if (item) {
  3299. this.doPlay(item);
  3300. }
  3301. }
  3302. })
  3303. Row() {
  3304. TextInput({ placeholder: '输入名称...', text: this.searchText })
  3305. .height(35)
  3306. .onChange((value: string) => {
  3307. this.onSearchInput(value);
  3308. })
  3309. .layoutWeight(1)
  3310. Text(`取消`)
  3311. .margin({ left: 10, right: 10 })
  3312. .fontColor($r('app.color.text_color'))
  3313. .fontSize(16)
  3314. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3315. .onClick(() => {
  3316. this.isSearchMode = false
  3317. this.searchText = ''
  3318. if(this.modeType==0){
  3319. this.updateListData(this.videoLocalList)
  3320. } else if(this.modeType==1){
  3321. this.updateListData(this.mediaKuList)
  3322. } else if(this.modeType==2&&!this.isCanBack){
  3323. this.updateListData(this.artistList)
  3324. } else if(this.modeType==3&&!this.isCanBack){
  3325. this.updateListData(this.albumList)
  3326. }else if(this.modeType==4){
  3327. this.doSongListTask()
  3328. }
  3329. })
  3330. }
  3331. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3332. .animation({
  3333. duration: 666,
  3334. curve: 'ease-in-out' // 可选动画曲线
  3335. })
  3336. Blank()
  3337. Image($r("app.media.search"))
  3338. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  3339. .animation({
  3340. duration: 666,
  3341. curve: 'ease-in-out' // 可选动画曲线
  3342. })// .opacity(this.opacityItem)
  3343. .fillColor(this.themeColor)
  3344. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3345. .onClick(() => {
  3346. this.isSearchMode = true
  3347. })
  3348. Image($r("app.media.refresh"))
  3349. .fillColor(this.themeColor)
  3350. .width(25)
  3351. .visibility(this.modeType ==4||this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3352. .animation({
  3353. duration: 666,
  3354. curve: 'ease-in-out' // 可选动画曲线
  3355. })
  3356. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3357. .onClick(() => {
  3358. if (this.isFavMusic) {
  3359. this.getFavList(true)
  3360. } else {
  3361. if(this.modeType == 0){
  3362. this.asyncCurrentPathData()
  3363. }else if(this.modeType ==1){
  3364. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3365. }
  3366. }
  3367. })
  3368. Image($r("app.media.top_rank"))
  3369. .width(25)
  3370. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  3371. Visibility.Visible)// .opacity(this.opacityItem)
  3372. .animation({
  3373. duration: 666,
  3374. curve: 'ease-in-out' // 可选动画曲线
  3375. })
  3376. .fillColor(this.themeColor)
  3377. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3378. .onClick(() => {
  3379. this.showRankDialog()
  3380. })
  3381. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  3382. .width(24)
  3383. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3384. .animation({
  3385. duration: 666,
  3386. curve: 'ease-in-out' // 可选动画曲线
  3387. })
  3388. .fillColor(this.themeColor)
  3389. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3390. .onClick(() => {
  3391. this.isMultiSelect = !this.isMultiSelect
  3392. })
  3393. SymbolGlyph($r('sys.symbol.trash'))
  3394. .fontColor([this.themeColor])
  3395. .fontSize(25)
  3396. .effectStrategy(1)
  3397. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  3398. .animation({
  3399. duration: 666,
  3400. curve: 'ease-in-out' // 可选动画曲线
  3401. })
  3402. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3403. .onClick(() => {
  3404. this.clearVideoHistory() //清空播放记录
  3405. })
  3406. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3407. .width(24)
  3408. .animation({
  3409. duration: 666,
  3410. curve: 'ease-in-out' // 可选动画曲线
  3411. })
  3412. .fillColor(this.themeColor)
  3413. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3414. .bindPopup($$this.tipPopup, {
  3415. builder: this.popupBuilder,
  3416. placement: Placement.Bottom,
  3417. maskColor: 0x33000000,
  3418. enableArrow: true,
  3419. onStateChange: (e) => {
  3420. if (!e.isVisible) {
  3421. this.tipPopup = false;
  3422. }
  3423. }
  3424. })
  3425. .onClick(() => {
  3426. if(this.twoFingerType==4){
  3427. this.isGridMusic = false
  3428. this.twoFingerType=3
  3429. }else{
  3430. this.isGridMusic = !this.isGridMusic
  3431. }
  3432. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3433. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3434. })
  3435. }
  3436. .width('100%')
  3437. .padding(10)
  3438. .height(50)
  3439. .visibility(this.modeType === 0 || this.modeType === 1||this.modeType === 4
  3440. || this.isCanBack ? Visibility.Visible : Visibility.None)
  3441. .border({
  3442. width: { bottom: 1 },
  3443. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3444. })
  3445. }
  3446. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3447. }
  3448. // 第二步:popup构造器定义弹框内容
  3449. @Builder popupBuilder() {
  3450. Column({ space: 2 }) {
  3451. Text('友情提示:双指缩放可以放大缩小列表')
  3452. .fontSize(12)
  3453. .fontWeight(FontWeight.Regular)
  3454. .fontColor($r('app.color.text_color'))
  3455. }
  3456. .justifyContent(FlexAlign.SpaceAround)
  3457. .width(220)
  3458. .height(55)
  3459. .padding(15)
  3460. }
  3461. //搜索功能的实现
  3462. @State searchText: string = ''; // 用户输入内容
  3463. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3464. @State isSearchMode: boolean = false
  3465. // 实时搜索逻辑(带防抖)
  3466. private onSearchInput(value: string) {
  3467. this.searchText = value.trim();
  3468. let mSearchList: Array<VideoItem> = []
  3469. switch (this.modeType) {
  3470. case 0:
  3471. // mSearchList = this.videoLocalList
  3472. // break;
  3473. case 1:
  3474. mSearchList = this.mediaKuList
  3475. break;
  3476. case 2:
  3477. mSearchList = this.artistList
  3478. break;
  3479. case 3:
  3480. mSearchList = this.albumList
  3481. break;
  3482. }
  3483. // 新增条件判断:空输入时显示所有数据
  3484. if (this.searchText === '') {
  3485. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3486. } else {
  3487. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3488. //支持模糊匹配和艺术家 专辑匹配
  3489. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  3490. return regex.test(item.name.toLowerCase())||
  3491. regex.test(item.fileName?.toLowerCase() ?? "") ||
  3492. regex.test(item.artist?.toLowerCase() ?? "") ||
  3493. regex.test(item.album?.toLowerCase() ?? "")
  3494. });
  3495. }
  3496. this.updateListData(this.filteredList);
  3497. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3498. }
  3499. @State dragItem: number = -1
  3500. @State scaleItem: number = -1
  3501. @State neighborItem: number = -1
  3502. @State neighborScale: number = -1
  3503. @State offsetY: number = 0
  3504. private dragRefOffset: number = 0
  3505. private ITEM_INTV: number = 78
  3506. scaleSelect(item: number): number {
  3507. if (this.scaleItem === item) {
  3508. return 1.05
  3509. } else if (this.neighborItem === item) {
  3510. return this.neighborScale
  3511. } else {
  3512. return 1
  3513. }
  3514. }
  3515. itemMove(index: number, newIndex: number): void {
  3516. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3517. return;
  3518. }
  3519. let tmp = this.videoLocalList.splice(index, 1);
  3520. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3521. this.dataSource.pushArrayData(this.videoLocalList)
  3522. if(this.modeType==4&&this.playlistTable){
  3523. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  3524. }
  3525. }
  3526. //瀑布流布局 支持双指缩放
  3527. @State columns: number = 2;
  3528. @State waterFlowScale: number = 1;
  3529. @State imageScale: number = 1;
  3530. @State waterFlowOpacity: number = 1;
  3531. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  3532. private columnChanged: boolean = false;
  3533. private oldColumn: number = this.columns;
  3534. private pinchTime: number = 0;
  3535. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  3536. changeColumns(scale: number) {
  3537. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3538. this.columns--;
  3539. this.columnChanged = true;
  3540. } else if (scale < 1 && this.columns < 4) {
  3541. this.columns++;
  3542. this.columnChanged = true;
  3543. }
  3544. }
  3545. @Builder
  3546. getWaterView(){
  3547. Scroll(this.scroller) {
  3548. Column() {
  3549. if(this.isShowCoverHeader()){
  3550. this.coverHeader()
  3551. }else {
  3552. this.listViewTitle()
  3553. }
  3554. WaterFlow({
  3555. scroller:this.waterScroller,
  3556. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  3557. }) {
  3558. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3559. FlowItem() {
  3560. this.MusicWaterCardItem(item,index)
  3561. }
  3562. .width('100%')
  3563. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3564. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3565. {
  3566. preview: MenuPreviewMode.IMAGE,
  3567. previewAnimationOptions: { scale: [0.8, 1.0] },
  3568. })
  3569. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3570. {
  3571. preview: MenuPreviewMode.IMAGE,
  3572. previewAnimationOptions: { scale: [0.8, 1.0] },
  3573. })
  3574. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  3575. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3576. TransitionEffect.scale({ x: 0, y: 0 })))
  3577. .gesture(
  3578. GestureGroup(GestureMode.Exclusive,
  3579. SwipeGesture({ direction: SwipeDirection.Horizontal })
  3580. .onAction((event: GestureEvent) => {
  3581. if (event) {
  3582. // this.sideBarController.openSideBar()
  3583. }
  3584. }),
  3585. TapGesture({ count: 1, fingers: 1 })
  3586. .onAction(async () => {
  3587. })
  3588. )
  3589. )
  3590. }, (item: VideoItem) => item.filePath)
  3591. }
  3592. // .columnsTemplate('repeat(auto-fit, 160)')
  3593. .id('waterflow') // 设置id用于截图
  3594. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  3595. .columnsGap(12) // 列间距
  3596. .rowsGap(16) // 行间距
  3597. .cachedCount(6)
  3598. // .margin(
  3599. // this.isHiCar()?{bottom:this.bottomBarHeight+90}:
  3600. // {bottom:this.isShowCoverHeader()? this.topBarHeight+35:
  3601. // this.isCoverOpacity()?this.topBarHeight+this.bottomBarHeight+78
  3602. // :this.topBarHeight+this.bottomBarHeight+108})
  3603. .margin({
  3604. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  3605. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  3606. })
  3607. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3608. .animation({ duration: 500, curve: Curve.Ease }))
  3609. .scrollBar(BarState.Off)
  3610. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  3611. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  3612. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  3613. .width('100%')
  3614. .height('100%')
  3615. .padding(10)
  3616. .opacity(this.waterFlowOpacity)
  3617. .scale({
  3618. x: this.waterFlowScale,
  3619. y: this.waterFlowScale,
  3620. centerX: 0,
  3621. centerY: 0
  3622. })
  3623. .onAppear(() => {
  3624. this.scroller.scrollEdge(Edge.Top)
  3625. })
  3626. .nestedScroll({
  3627. scrollForward: NestedScrollMode.PARENT_FIRST,
  3628. scrollBackward: NestedScrollMode.SELF_FIRST
  3629. })
  3630. .priorityGesture(
  3631. PinchGesture()
  3632. .onActionStart((event: GestureEvent) => {
  3633. // 双指捏合手势识别成功时截图
  3634. this.pinchTime = event.timestamp;
  3635. this.columnChanged = false;
  3636. this.oldColumn = this.columns;
  3637. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  3638. if (error) {
  3639. console.info('error:' + JSON.stringify(error));
  3640. return;
  3641. }
  3642. this.waterFlowSnapshot = pixmap;
  3643. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  3644. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  3645. if (this.oldColumn ===4) {
  3646. this.twoFingerType =3
  3647. this.isGridMusic = true
  3648. }else if (this.oldColumn ===1) {
  3649. this.twoFingerType =1
  3650. this.isGridMusic = false
  3651. }
  3652. return;
  3653. }
  3654. })
  3655. })
  3656. .onActionUpdate((event: GestureEvent) => {
  3657. // 手势更新:处理缩放逻辑和视觉效果
  3658. // 边界限制:防止超出列数范围时继续缩放
  3659. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  3660. return;
  3661. }
  3662. // 节流处理:避免过于频繁的更新,提升性能
  3663. if (event.timestamp - this.pinchTime < 10000000) {
  3664. return;
  3665. }
  3666. this.pinchTime = event.timestamp;
  3667. this.waterFlowScale = event.scale;
  3668. this.imageScale = event.scale;
  3669. // 根据缩放比例设置WaterFlow透明度
  3670. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  3671. this.waterFlowOpacity *= 3;
  3672. if (!this.columnChanged) {
  3673. this.changeColumns(event.scale);
  3674. }
  3675. // 列数改变后的缩放比例调整:避免出现空白区域
  3676. if (this.columnChanged) {
  3677. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  3678. // 限制缩放范围,确保视觉效果自然
  3679. if (event.scale < 1) {
  3680. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  3681. } else {
  3682. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  3683. }
  3684. }
  3685. })
  3686. .onActionEnd((event: GestureEvent) => {
  3687. // 手势结束:执行归位动画并保存状态
  3688. // 执行归位动画:平滑过渡到正常状态
  3689. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  3690. this.waterFlowScale = 1;
  3691. this.waterFlowOpacity = 1;
  3692. })
  3693. // 持久化保存当前列数:下次启动时恢复
  3694. PreferencesUtil.putSync('lastColumns', this.columns);
  3695. })
  3696. )
  3697. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3698. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3699. .onDrop((event?: DragEvent) => {
  3700. try {
  3701. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3702. if (dragData !== undefined) {
  3703. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3704. if (records.length > 0) {
  3705. for (let i = 0; i < records.length; i++) {
  3706. let types = records[i].getTypes();
  3707. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3708. const fileUriUds =
  3709. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3710. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3711. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3712. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3713. this.targetFile = fileUriUds.oriUri;
  3714. this.saveVideoDatas([this.targetFile])
  3715. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3716. }
  3717. }
  3718. }
  3719. } else {
  3720. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3721. }
  3722. } else {
  3723. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3724. }
  3725. } catch (error) {
  3726. const err = error as BusinessError;
  3727. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3728. }
  3729. })
  3730. }
  3731. }
  3732. .scrollBar(BarState.Off)
  3733. }
  3734. //瀑布流卡片布局
  3735. @Builder
  3736. private MusicWaterCardItem(item: VideoItem, index: number) {
  3737. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3738. Stack() {
  3739. Column() {
  3740. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3741. .backgroundImageSize(ImageSize.Auto)
  3742. .borderRadius({
  3743. topLeft: 12,
  3744. topRight : 12,
  3745. bottomLeft: 0,
  3746. bottomRight: 0
  3747. })
  3748. .draggable(false)// 禁止长按手势拖动
  3749. // .autoResize(true) // 重采样,可减少内存占用
  3750. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3751. .width('100%')
  3752. .height('auto')
  3753. .objectFit(ImageFit.Auto)
  3754. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3755. height: '99%' ,
  3756. dragBar: true,
  3757. onDisappear: () => {
  3758. this.longItemFilePath = '';
  3759. this.tempLyricContent = ''
  3760. },
  3761. showClose: true,
  3762. preferType: SheetType.CENTER ,
  3763. title: { title: '编辑标签' }
  3764. })
  3765. .draggable(false)
  3766. .opacity(this.opacityItem)// 绑定透明度
  3767. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3768. // .animation({ duration: 500, curve: Curve.Ease }))
  3769. .animation({
  3770. duration: 666,
  3771. curve: 'ease-in-out' // 可选动画曲线
  3772. })
  3773. .margin({
  3774. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3775. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3776. })
  3777. Column() {
  3778. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3779. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  3780. .maxLines(1)
  3781. .fontWeight(FontWeight.Bold)
  3782. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3783. .animation({
  3784. duration: 555,
  3785. curve: 'Linear',
  3786. })
  3787. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3788. height: '95%',
  3789. dragBar: true,
  3790. showClose: true,
  3791. onDisappear: () => {
  3792. this.longItemFilePathDetail = '';
  3793. },
  3794. blurStyle:BlurStyle.Thin,
  3795. backgroundColor:Color.Transparent,
  3796. preferType: SheetType.CENTER ,
  3797. title: { title: '详情' }
  3798. })
  3799. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3800. $r('app.color.text_color'))
  3801. Column() {
  3802. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3803. .fontSize(11)
  3804. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3805. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3806. .fontColor($r('app.color.text_color'))
  3807. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3808. .fontSize(11)
  3809. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3810. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3811. .fontColor($r('app.color.text_color'))
  3812. Row(){
  3813. Column(){
  3814. Text(item.md5Str?.includes('Lossless')?
  3815. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3816. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  3817. .padding({ top: 3,right:6,left:6,bottom:3 })
  3818. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3819. $r('app.color.text_color'))
  3820. .fontWeight(500)
  3821. .borderRadius(12)
  3822. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3823. .backgroundColor('#FFC107')
  3824. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  3825. }
  3826. .margin({ top: 2 ,right:6})
  3827. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3828. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3829. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3830. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  3831. .maxLines(1)
  3832. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3833. .margin({ top: 2})
  3834. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3835. || item.type == CommonConstants.TYPE_IS_ALBUM
  3836. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3837. .fontWeight(FontWeight.Medium)
  3838. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3839. $r('app.color.text_color'))
  3840. }
  3841. }
  3842. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3843. }
  3844. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  3845. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  3846. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  3847. .width('100%')
  3848. .justifyContent(FlexAlign.Center)
  3849. .margin({
  3850. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3851. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3852. })
  3853. }
  3854. .width('100%')
  3855. .borderRadius(12)
  3856. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3857. .backgroundImageSize({ height: '100%', width: '100%' })
  3858. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3859. .animation({ curve: Curve.Sharp, duration: 300 })
  3860. Checkbox({ name: 'checkbox' + index })
  3861. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3862. .selectedColor(this.themeColor)
  3863. .shape(CheckBoxShape.CIRCLE)
  3864. .opacity(this.isMultiSelect ? 1 : 0)
  3865. .animation({
  3866. duration: 666,
  3867. curve: 'Smooth' // 可选动画曲线
  3868. })
  3869. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3870. Visibility.None)
  3871. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3872. .margin({ left: 20, top: 8, bottom: 8 })
  3873. .width(38)
  3874. .height(38)
  3875. }
  3876. }
  3877. .backgroundColor(Color.Transparent)
  3878. .width('100%')
  3879. .height('auto')
  3880. .padding({top:2})
  3881. .reuseId('card_item')
  3882. .onClick(() => {
  3883. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3884. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3885. this.handleFileSelection(item, !isChecked);
  3886. } else {
  3887. this.doPlay(item, index)
  3888. }
  3889. })
  3890. }
  3891. // Grid布局的开始
  3892. private dragRefOffSetX: number = 0;
  3893. private dragRefOffSetY: number = 0;
  3894. private FIX_VP_X: number = 180;
  3895. private FIX_VP_Y: number = 84;
  3896. isDraggable(index: number): boolean {
  3897. return index >= 0;
  3898. }
  3899. getRowEnd(item: number) {
  3900. if (item.toString() === '0') {
  3901. return 1;
  3902. } else {
  3903. return 0;
  3904. }
  3905. }
  3906. isInLeft(index: number) {
  3907. return index % 2 == 0;
  3908. }
  3909. down(index: number): void {
  3910. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  3911. return;
  3912. }
  3913. this.offsetY -= this.FIX_VP_Y;
  3914. this.dragRefOffSetY += this.FIX_VP_Y;
  3915. this.itemMove(index, index + 1);
  3916. }
  3917. up(index: number): void {
  3918. if (!this.isDraggable(index - 2)) {
  3919. return;
  3920. }
  3921. this.offsetY += this.FIX_VP_Y;
  3922. this.dragRefOffSetY -= this.FIX_VP_Y;
  3923. this.itemMove(index, index - 1);
  3924. }
  3925. left(index: number): void {
  3926. if (this.isInLeft(index)) {
  3927. return;
  3928. }
  3929. if (!this.isDraggable(index - 1)) {
  3930. return;
  3931. }
  3932. this.offsetX += this.FIX_VP_X;
  3933. this.dragRefOffSetX -= this.FIX_VP_X;
  3934. this.itemMove(index, index - 1)
  3935. }
  3936. right(index: number): void {
  3937. if (!this.isInLeft(index)) {
  3938. return;
  3939. }
  3940. if (!this.isDraggable(index + 1)) {
  3941. return;
  3942. }
  3943. this.offsetX -= this.FIX_VP_X;
  3944. this.dragRefOffSetX += this.FIX_VP_X;
  3945. this.itemMove(index, index + 1)
  3946. }
  3947. private scroller: Scroller = new Scroller();
  3948. private waterScroller: Scroller = new Scroller();
  3949. @State startIndex: number = 0
  3950. @State endIndex: number = 0
  3951. @State scaleValue: number = 1
  3952. @State pinchValue: number = 1
  3953. layoutOptionsForHeader: GridLayoutOptions = {
  3954. regularSize: [1, 1], // 只支持[1, 1]
  3955. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3956. };
  3957. @Builder
  3958. getGridView() {
  3959. Grid(this.scroller, this.layoutOptionsForHeader) {
  3960. GridItem() {
  3961. if (this.isShowCoverHeader()) {
  3962. this.coverHeader()
  3963. } else {
  3964. this.listViewTitle()
  3965. }
  3966. }
  3967. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3968. GridItem() {
  3969. Stack({ alignContent: Alignment.Center }) {
  3970. this.MusicItemGrid(item, index)
  3971. }
  3972. }
  3973. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3974. {
  3975. preview: MenuPreviewMode.IMAGE,
  3976. previewAnimationOptions: { scale: [0.8, 1.0] },
  3977. })
  3978. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3979. {
  3980. preview: MenuPreviewMode.IMAGE,
  3981. previewAnimationOptions: { scale: [0.8, 1.0] },
  3982. })
  3983. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3984. TransitionEffect.scale({ x: 0, y: 0 })))
  3985. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3986. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3987. .zIndex(this.dragItem === index ? 1 : 0)
  3988. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3989. }, (item: VideoItem) => item.filePath)
  3990. }
  3991. .width(this.isShowHeader ? '100%' : '94%')
  3992. .height('100%')
  3993. .editMode(true)
  3994. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3995. .animation({ duration: 500, curve: Curve.Ease }))
  3996. .margin(
  3997. this.isHiCar()?{bottom:this.bottomBarHeight+98}:
  3998. {
  3999. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  4000. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  4001. })
  4002. .reuseId('grid_item')
  4003. .layoutWeight(1)
  4004. .scrollBar(BarState.Off)
  4005. .supportAnimation(true)
  4006. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  4007. .columnsTemplate(
  4008. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  4009. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  4010. )
  4011. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  4012. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  4013. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4014. .gesture(PinchGesture({ fingers: 2 })
  4015. .onActionEnd((event: GestureEvent) => {
  4016. this.setGridTwoFingers()
  4017. })
  4018. .onActionUpdate(e => {
  4019. this.scaleValue = this.pinchValue * e.scale
  4020. })
  4021. .onActionStart(e => {
  4022. }))
  4023. .enableScrollInteraction(true)
  4024. .onScrollIndex((start: number, end: number) => {
  4025. this.startIndex = start
  4026. this.endIndex = end
  4027. })
  4028. .onScrollFrameBegin((offset: number) => {
  4029. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4030. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4031. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4032. if (this.isScrollHide) {
  4033. this.setBarHeightHide2(offset)
  4034. } else {
  4035. this.setBarHeightNormal()
  4036. }
  4037. } else {
  4038. this.setBarHeightHide(offset)
  4039. }
  4040. return { offsetRemain: offset };
  4041. })
  4042. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4043. .onDrop((event?: DragEvent) => {
  4044. try {
  4045. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4046. if (dragData !== undefined) {
  4047. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4048. if (records.length > 0) {
  4049. for (let i = 0; i < records.length; i++) {
  4050. let types = records[i].getTypes();
  4051. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4052. const fileUriUds =
  4053. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4054. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4055. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4056. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4057. this.targetFile = fileUriUds.oriUri;
  4058. this.saveVideoDatas([this.targetFile])
  4059. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4060. }
  4061. }
  4062. }
  4063. } else {
  4064. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4065. }
  4066. } else {
  4067. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4068. }
  4069. } catch (error) {
  4070. const err = error as BusinessError;
  4071. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4072. }
  4073. })
  4074. }
  4075. @State targetFile: string = '';
  4076. setGridTwoFingers() {
  4077. this.pinchValue = this.scaleValue;
  4078. Logger.info('this.pinchValue = ' + this.pinchValue);
  4079. if (this.pinchValue >= 1) {
  4080. this.twoFingerType++
  4081. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4082. if(this.twoFingerType >= 4){
  4083. this.twoFingerType = 4//切换成瀑布流
  4084. this.columns = 4
  4085. }
  4086. } else {
  4087. this.twoFingerType--
  4088. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4089. if (this.twoFingerType < 1) {
  4090. this.twoFingerType = 3
  4091. this.isGridMusic = false
  4092. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4093. }
  4094. }
  4095. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4096. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4097. this.pinchValue = 1;
  4098. this.scaleValue = 1;
  4099. }
  4100. @State longItemFilePath: string = ''
  4101. @State tempLyricContent: string = ''
  4102. @Builder
  4103. private MusicItemGrid(item: VideoItem, index: number) {
  4104. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4105. Stack() {
  4106. Column() {
  4107. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  4108. .height(this.getGridHeight())
  4109. .width(this.getGridWight())
  4110. .draggable(false)
  4111. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4112. .autoResize(true) // 重采样,可减少内存占用
  4113. .alt($r('app.media.ic_avatar2'))
  4114. .clip(true)
  4115. .borderRadius({
  4116. topLeft: 12,
  4117. topRight: 12,
  4118. bottomLeft: 0,
  4119. bottomRight: 0
  4120. })
  4121. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4122. height: '99%' ,
  4123. dragBar: true,
  4124. onDisappear: () => {
  4125. this.longItemFilePath = '';
  4126. this.tempLyricContent = ''
  4127. },
  4128. showClose: true,
  4129. preferType: SheetType.CENTER ,
  4130. title: { title: '编辑标签' }
  4131. })
  4132. .draggable(false)
  4133. .opacity(this.opacityItem)// 绑定透明度
  4134. .animation({
  4135. duration: 666,
  4136. curve: 'ease-in-out' // 可选动画曲线
  4137. })
  4138. .margin({
  4139. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4140. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4141. })
  4142. Column() {
  4143. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4144. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4145. .maxLines(1)
  4146. .fontWeight(FontWeight.Bold)
  4147. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4148. .animation({
  4149. duration: 555,
  4150. curve: 'Linear',
  4151. })
  4152. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4153. height: '95%',
  4154. dragBar: true,
  4155. showClose: true,
  4156. onDisappear: () => {
  4157. this.longItemFilePathDetail = '';
  4158. },
  4159. blurStyle:BlurStyle.Thin,
  4160. backgroundColor:Color.Transparent,
  4161. preferType: SheetType.CENTER ,
  4162. title: { title: '详情' }
  4163. })
  4164. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4165. $r('app.color.text_color'))
  4166. Column() {
  4167. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4168. .fontSize(11)
  4169. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4170. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4171. .fontColor($r('app.color.text_color'))
  4172. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4173. .fontSize(11)
  4174. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4175. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4176. .fontColor($r('app.color.text_color'))
  4177. Row(){
  4178. Column(){
  4179. Text(item.md5Str?.includes('Lossless')?
  4180. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4181. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4182. .padding({ top: 3,right:6,left:6,bottom:3 })
  4183. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4184. $r('app.color.text_color'))
  4185. .fontWeight(500)
  4186. .borderRadius(12)
  4187. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4188. .backgroundColor('#FFC107')
  4189. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4190. }
  4191. .margin({ top: 2 ,right:6})
  4192. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4193. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4194. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4195. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  4196. .maxLines(1)
  4197. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4198. .margin({ top: 2})
  4199. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4200. || item.type == CommonConstants.TYPE_IS_ALBUM
  4201. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4202. .fontWeight(FontWeight.Medium)
  4203. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4204. $r('app.color.text_color'))
  4205. }
  4206. }
  4207. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4208. }
  4209. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  4210. .width(this.getGridWight())
  4211. .justifyContent(FlexAlign.Center)
  4212. .margin({
  4213. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4214. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4215. })
  4216. }
  4217. .width(this.getGridWight())
  4218. .borderRadius(12)
  4219. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  4220. .backgroundImageSize({ height: '100%', width: '100%' })
  4221. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4222. .animation({ curve: Curve.Sharp, duration: 300 })
  4223. Checkbox({ name: 'checkbox' + index })
  4224. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4225. .selectedColor(this.themeColor)
  4226. .shape(CheckBoxShape.CIRCLE)
  4227. .opacity(this.isMultiSelect ? 1 : 0)
  4228. .animation({
  4229. duration: 666,
  4230. curve: 'Smooth' // 可选动画曲线
  4231. })
  4232. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4233. Visibility.None)
  4234. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4235. .margin({ left: 20, top: 8, bottom: 8 })
  4236. .width(38)
  4237. .height(38)
  4238. }
  4239. }
  4240. .backgroundColor(Color.Transparent)
  4241. .width('100%')
  4242. .padding({ top: 15 })
  4243. .height(this.getGridAllHeight())
  4244. .onClick(() => {
  4245. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4246. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4247. this.handleFileSelection(item, !isChecked);
  4248. } else {
  4249. this.doPlay(item, index)
  4250. }
  4251. })
  4252. }
  4253. getGridAllHeight() {
  4254. let heightG = 222
  4255. switch (this.twoFingerType) {
  4256. case 1:
  4257. heightG = 143
  4258. break;
  4259. case 2:
  4260. heightG = 178
  4261. break;
  4262. case 3:
  4263. heightG = 222
  4264. break;
  4265. }
  4266. return heightG
  4267. }
  4268. getGridHeight() {
  4269. let heightG = 150
  4270. switch (this.twoFingerType) {
  4271. case 1:
  4272. heightG = 80
  4273. break;
  4274. case 2:
  4275. heightG = 110
  4276. break;
  4277. case 3:
  4278. heightG = 150
  4279. break;
  4280. }
  4281. return heightG
  4282. }
  4283. getGridWight() {
  4284. let wightG = 158
  4285. switch (this.twoFingerType) {
  4286. case 1:
  4287. wightG = 80
  4288. break;
  4289. case 2:
  4290. wightG = 110
  4291. break;
  4292. case 3:
  4293. wightG = 158
  4294. break;
  4295. }
  4296. return wightG
  4297. }
  4298. @State isShowDetail:boolean = false
  4299. @State longItemFilePathDetail:string =''
  4300. @Builder
  4301. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  4302. if(
  4303. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4304. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4305. item.name === LocalMusic.STR_HISTORY_MUSIC)
  4306. ){
  4307. //如果是专辑和艺术家的首页,不能长按
  4308. //如果是我的收藏 最近播放等也不能长按
  4309. }else{
  4310. Scroll() {
  4311. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  4312. Menu() {
  4313. MenuItem({
  4314. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  4315. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  4316. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  4317. })
  4318. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4319. .onClick(() => {
  4320. if (item) {
  4321. this.doFav(item)
  4322. }
  4323. this.longItemFilePath = ''
  4324. })
  4325. MenuItem({
  4326. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  4327. content: '下一首播放'
  4328. })
  4329. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4330. .onClick(() => {
  4331. this.addToNextPlay(item);
  4332. this.longItemFilePath = ''
  4333. })
  4334. MenuItem({
  4335. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  4336. content: '添加到歌单'
  4337. })
  4338. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4339. .onClick(async () => {
  4340. this.longItemFilePath = ''
  4341. await this.showAddToPlaylistDialog(item)
  4342. })
  4343. MenuItem({
  4344. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  4345. content: '编辑标签'
  4346. })
  4347. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  4348. height: '99%',
  4349. dragBar: true,
  4350. showClose: true,
  4351. preferType: SheetType.CENTER ,
  4352. title: { title: '编辑标签' }
  4353. })
  4354. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4355. .onClick(async() => {
  4356. this.setEditStrEmpty()
  4357. this.tempLyricContent = await this.getLyricContent(item);
  4358. if(this.isGridMusic||this.twoFingerType==4){
  4359. this.longItemFilePath = item.filePath
  4360. }else{
  4361. this.isShowEdit = !this.isShowEdit;
  4362. }
  4363. })
  4364. MenuItem({
  4365. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  4366. content: $r('app.string.select_all')
  4367. })
  4368. .onClick(() => {
  4369. this.isMultiSelect = !this.isMultiSelect
  4370. this.longItemFilePath = ''
  4371. this.selectedFiles.push(item)
  4372. })
  4373. MenuItem({
  4374. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  4375. content: $r('app.string.rename')
  4376. })
  4377. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4378. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4379. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4380. .onClick(() => {
  4381. this.showReNameDialog(item, index + '', filePath)
  4382. this.longItemFilePath = ''
  4383. })
  4384. MenuItem({
  4385. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  4386. content: $r('app.string.delete')
  4387. })
  4388. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4389. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4390. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4391. .onClick(() => {
  4392. this.selectedFiles.push(item)
  4393. this.showWarnIsDelete()
  4394. this.longItemFilePath = ''
  4395. })
  4396. MenuItem({
  4397. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  4398. content: $r('app.string.detail')
  4399. })
  4400. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  4401. height:'95%',
  4402. dragBar: true,
  4403. showClose: true,
  4404. blurStyle:BlurStyle.Thin,
  4405. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4406. backgroundColor:Color.Transparent,
  4407. title: { title: '详情信息' }
  4408. })
  4409. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4410. .onClick(() => {
  4411. if(this.isGridMusic||this.twoFingerType==4){
  4412. this.longItemFilePathDetail = item.filePath
  4413. }else{
  4414. this.isShowDetail = !this.isShowDetail
  4415. }
  4416. })
  4417. MenuItem({
  4418. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  4419. content: $r('app.string.share')
  4420. })
  4421. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4422. .onClick(() => {
  4423. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4424. this.longItemFilePath = ''
  4425. })
  4426. }
  4427. .font({ size: 15, weight: FontWeight.Normal })
  4428. }
  4429. .width(180)
  4430. }
  4431. .height('auto')
  4432. }
  4433. }
  4434. private listMaxScrollOffsetY: number = 0
  4435. @State selectedIndex: number = -1
  4436. setlistTwoFingers() {
  4437. this.pinchValue = this.scaleValue;
  4438. Logger.info('this.pinchValue = ' + this.pinchValue);
  4439. if (this.pinchValue >= 1) {
  4440. this.twoFingerType++
  4441. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4442. if (this.twoFingerType > 3) {
  4443. this.twoFingerType = 1
  4444. this.isGridMusic = true
  4445. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4446. }
  4447. } else {
  4448. this.twoFingerType--
  4449. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4450. if (this.twoFingerType < 1) {
  4451. this.twoFingerType = 4
  4452. this.columns = 1
  4453. }
  4454. }
  4455. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4456. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4457. this.pinchValue = 1;
  4458. this.scaleValue = 1;
  4459. }
  4460. @Builder
  4461. getList(){
  4462. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  4463. this.getListView()
  4464. }
  4465. .pullDownRatio(this.ratioL)
  4466. .pullToRefresh(true)
  4467. .refreshOffset(0)
  4468. .onOffsetChange((offset: number) => {
  4469. // 越接近最大距离,下拉跟手系数越小。
  4470. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  4471. })
  4472. .onStateChange((refreshStatus: RefreshStatus) => {
  4473. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  4474. })
  4475. .onRefreshing(async () => {
  4476. if(this.modeType==0){
  4477. this.getHistoryList(false)
  4478. this.asyncCurrentPathOnlyFile()
  4479. }else if(this.modeType == 1){
  4480. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4481. }else if(this.modeType == 2){
  4482. workerInstance.postMessage({ code: 3, data: this.context });
  4483. }else if(this.modeType == 3){
  4484. workerInstance.postMessage({ code: 4, data: this.context });
  4485. }else if(this.modeType == 4){
  4486. this.doSongListTask()
  4487. }
  4488. console.log('onRefreshing test');
  4489. })
  4490. }
  4491. // 扫描当前目录下的文件,不扫描子目录
  4492. asyncCurrentPathOnlyFile(){
  4493. if(this.modeType==0){
  4494. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  4495. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  4496. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  4497. if(this.modeType==0){
  4498. this.getSortedFiles(this.currentPath)
  4499. }
  4500. setTimeout(() => {
  4501. this.isRefreshing = false;
  4502. }, 100)
  4503. }).catch((e:object)=>{
  4504. console.info("task1 catch e: " + e);
  4505. })
  4506. }
  4507. }
  4508. @Builder
  4509. getListView() {
  4510. List({ scroller: this.listScroller }) {
  4511. ListItemGroup({ header: this.coverHeader() }) {
  4512. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4513. ListItem() {
  4514. Column() {
  4515. if (item.type === CommonConstants.TYPE_IS_DIR
  4516. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  4517. this.DirItem(item, index)
  4518. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  4519. } else {
  4520. this.MusicItem(item, index)
  4521. }
  4522. }
  4523. .shadow(this.scaleItem === index ? {
  4524. radius: 70,
  4525. color: '#15000000',
  4526. offsetX: 0,
  4527. offsetY: 0
  4528. } :
  4529. {
  4530. radius: 0,
  4531. color: '#15000000',
  4532. offsetX: 0,
  4533. offsetY: 0
  4534. })
  4535. .animation({ curve: Curve.Sharp, duration: 300 })
  4536. }
  4537. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  4538. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  4539. .animation({ duration: 500 }),
  4540. TransitionEffect.scale({ x: 0, y: 0 })))
  4541. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4542. .swipeAction((
  4543. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  4544. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  4545. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  4546. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  4547. .onClick(() => {
  4548. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4549. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4550. this.handleFileSelection(item, !isChecked);
  4551. } else {
  4552. this.doPlay(item, index)
  4553. }
  4554. })
  4555. //拖动List关键代码开始
  4556. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4557. .zIndex(this.dragItem === index ? 1 : 0)
  4558. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4559. .gesture(
  4560. GestureGroup(GestureMode.Sequence,
  4561. LongPressGesture({ repeat: true })
  4562. .onAction((event?: GestureEvent) => {
  4563. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4564. this.scaleItem = index
  4565. })
  4566. })
  4567. .onActionEnd(() => {
  4568. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4569. this.scaleItem = -1
  4570. })
  4571. }),
  4572. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4573. .onActionStart(() => {
  4574. this.dragItem = index // 记录当前拖动项索引
  4575. this.dragRefOffset = 0 // 重置偏移基准
  4576. })
  4577. .onActionUpdate((event: GestureEvent) => {
  4578. this.offsetY = event.offsetY - this.dragRefOffset;
  4579. this.neighborItem = -1;
  4580. let indexA = this.videoLocalList.indexOf(item);
  4581. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4582. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4583. let value: number = 0;
  4584. if (this.offsetY < 0) {
  4585. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4586. this.neighborItem = indexA - 1;
  4587. this.neighborScale = 1 - value / 20;
  4588. } else if (this.offsetY > 0) {
  4589. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4590. this.neighborItem = indexA + 1;
  4591. this.neighborScale = 1 - value / 20;
  4592. }
  4593. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  4594. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4595. this.offsetY -= this.ITEM_INTV;
  4596. this.dragRefOffset += this.ITEM_INTV;
  4597. this.itemMove(indexA, indexA + 1);
  4598. });
  4599. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4600. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4601. this.offsetY += this.ITEM_INTV;
  4602. this.dragRefOffset -= this.ITEM_INTV;
  4603. this.itemMove(indexA, indexA - 1);
  4604. });
  4605. }
  4606. let curListOffset = this.listScroller.currentOffset()
  4607. // 获取手指信息
  4608. let fingerInfo = event.fingerList[0]
  4609. let clickPercentY =
  4610. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  4611. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  4612. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  4613. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  4614. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  4615. }
  4616. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  4617. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  4618. if (curListOffset.yOffset > scrollVelocity + 5) {
  4619. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  4620. }
  4621. }
  4622. })
  4623. .onActionEnd((event: GestureEvent) => {
  4624. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4625. this.dragItem = -1
  4626. this.neighborItem = -1
  4627. })
  4628. animateTo({
  4629. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4630. }, () => {
  4631. this.scaleItem = -1
  4632. })
  4633. })
  4634. )
  4635. .onCancel(() => {
  4636. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4637. this.dragItem = -1
  4638. this.neighborItem = -1
  4639. })
  4640. animateTo({
  4641. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4642. }, () => {
  4643. this.scaleItem = -1
  4644. })
  4645. })
  4646. ) //拖动List关键代码结束
  4647. }, (item: VideoItem) => item.filePath)
  4648. }
  4649. }
  4650. .scrollBar(BarState.Off)
  4651. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4652. .gesture(PinchGesture({ fingers: 2 })
  4653. .onActionEnd((event: GestureEvent) => {
  4654. this.setlistTwoFingers()
  4655. })
  4656. .onActionUpdate(e => {
  4657. this.scaleValue = this.pinchValue * e.scale
  4658. })
  4659. .onActionStart(e => {
  4660. }))
  4661. // .margin(
  4662. // this.isHiCar()&&(this.windowWidth>1800&&this.windowHeight>=1200)?{bottom:this.bottomBarHeight+98}:
  4663. // {
  4664. // bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  4665. // : (this.isShowCoverHeader() ? this.topBarHeight+35 :
  4666. // this.isHiCarSmall()||this.modeType==4?this.topBarHeight+90:this.topBarHeight+165)
  4667. // })
  4668. .margin({
  4669. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  4670. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  4671. })
  4672. .cachedCount(6)
  4673. .reuseId('list_item')
  4674. .borderRadius(20)
  4675. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4676. TransitionEffect.scale({ x: 0, y: 0 })))
  4677. .layoutWeight(1)
  4678. .onScrollIndex((start) => {
  4679. this.selectedIndex = start
  4680. })
  4681. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  4682. .lanes(
  4683. new BreakpointType<number>({
  4684. sm: 1,
  4685. md: 2,
  4686. lg: 2,
  4687. xl: 3,
  4688. xxl: 4
  4689. }).getValue(this.currentBreakpoint),
  4690. new BreakpointType<number>({
  4691. sm: 0,
  4692. md: 12,
  4693. lg: 12,
  4694. xl: 16,
  4695. xxl: 20
  4696. }).getValue(this.currentBreakpoint)
  4697. )
  4698. .onAreaChange((oldValue: Area, newValue: Area) => {
  4699. this.listArea = newValue
  4700. if (this.twoFingerType == 3) {
  4701. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  4702. } else if (this.twoFingerType == 2) {
  4703. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  4704. } else if (this.twoFingerType == 1) {
  4705. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  4706. }
  4707. })
  4708. .onScrollFrameBegin((offset: number) => {
  4709. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  4710. // if (this.isPhoneLan()) {
  4711. // this.setBarHeightHide(offset)
  4712. // } else
  4713. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4714. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4715. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4716. if (this.isScrollHide) {
  4717. this.setBarHeightHide2(offset)
  4718. } else {
  4719. this.setBarHeightNormal()
  4720. }
  4721. } else {
  4722. this.setBarHeightHide(offset)
  4723. }
  4724. return { offsetRemain: offset };
  4725. })
  4726. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  4727. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4728. .onDrop((event?: DragEvent) => {
  4729. try {
  4730. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4731. if (dragData !== undefined) {
  4732. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4733. if (records.length > 0) {
  4734. for (let i = 0; i < records.length; i++) {
  4735. let types = records[i].getTypes();
  4736. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4737. const fileUriUds =
  4738. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4739. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4740. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4741. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4742. this.targetFile = fileUriUds.oriUri;
  4743. this.saveVideoDatas([this.targetFile])
  4744. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4745. }
  4746. }
  4747. }
  4748. } else {
  4749. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4750. }
  4751. } else {
  4752. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4753. }
  4754. } catch (error) {
  4755. const err = error as BusinessError;
  4756. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4757. }
  4758. })
  4759. }
  4760. setBarHeightNormal() {
  4761. this.hideDone = false;
  4762. this.getUIContext().animateTo({
  4763. duration: 300
  4764. }, () => {
  4765. this.bottomBarHeight = 55 + 0;
  4766. this.topBarHeight = 50 + 0;
  4767. this.barOpacity = 1;
  4768. this.barBottomOpacity = 1
  4769. this.currentYOffset = 0;
  4770. this.isHiding = false;
  4771. });
  4772. }
  4773. setBarHeightHide(offset: number) {
  4774. if (offset > 0 && !this.hideDone) {
  4775. this.currentYOffset += offset;
  4776. if (this.currentYOffset <= 100) {
  4777. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  4778. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4779. this.barOpacity = 1 - this.currentYOffset / 100;
  4780. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  4781. } else {
  4782. this.topBarHeight = 0;
  4783. this.bottomBarHeight = 0;
  4784. this.barBottomOpacity = 0
  4785. this.barOpacity = 0;
  4786. this.hideDone = true;
  4787. }
  4788. this.isHiding = true;
  4789. }
  4790. if (offset < 0 && this.isHiding) {
  4791. this.hideDone = false;
  4792. this.getUIContext().animateTo({
  4793. duration: 300
  4794. }, () => {
  4795. this.bottomBarHeight = 55 + 0;
  4796. this.topBarHeight = 50 + 0;
  4797. this.barOpacity = 1;
  4798. this.barBottomOpacity = 1
  4799. this.currentYOffset = 0;
  4800. this.isHiding = false;
  4801. });
  4802. }
  4803. }
  4804. //这个方法没隐藏bottomBar,只隐藏topbar
  4805. setBarHeightHide2(offset: number) {
  4806. if (offset > 0 && !this.hideDone) {
  4807. this.currentYOffset += offset;
  4808. if (this.currentYOffset <= 100) {
  4809. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4810. this.barOpacity = 1 - this.currentYOffset / 100;
  4811. } else {
  4812. this.topBarHeight = 0;
  4813. this.barOpacity = 0;
  4814. this.hideDone = true;
  4815. }
  4816. this.isHiding = true;
  4817. }
  4818. if (offset < 0 && this.isHiding) {
  4819. this.hideDone = false;
  4820. this.getUIContext().animateTo({
  4821. duration: 300
  4822. }, () => {
  4823. this.topBarHeight = 50 + 0;
  4824. this.barOpacity = 1;
  4825. this.currentYOffset = 0;
  4826. this.isHiding = false;
  4827. });
  4828. }
  4829. }
  4830. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  4831. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  4832. switch (item.type) {
  4833. case CommonConstants.TYPE_IS_DIR:
  4834. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  4835. let offsetB = 0
  4836. if(this.twoFingerType==4){
  4837. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4838. let cur = this.waterScroller.currentOffset()
  4839. if (cur && typeof cur.yOffset === 'number') {
  4840. offsetB = cur.yOffset
  4841. }
  4842. }
  4843. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  4844. }else
  4845. if (this.isGridMusic) {
  4846. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4847. let cur = this.scroller.currentOffset()
  4848. if (cur && typeof cur.yOffset === 'number') {
  4849. offsetB = cur.yOffset
  4850. }
  4851. }
  4852. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  4853. } else {
  4854. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4855. let cur = this.listScroller.currentOffset()
  4856. if (cur && typeof cur.yOffset === 'number') {
  4857. offsetB = cur.yOffset
  4858. }
  4859. }
  4860. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  4861. }
  4862. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  4863. this.showVerifyDialog()
  4864. this.currentTitleName = '私密音频'
  4865. this.currentTitleCover = $r('app.media.ic_avatar5')
  4866. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  4867. this.titleBarModel.setTitleName('最近播放')
  4868. this.currentTitleCover = $r('app.media.ic_avatar2')
  4869. this.currentTitleName = '最近播放'
  4870. //加载动画效果
  4871. this.updateListData(this.historyList, true)
  4872. // this.videoLocalList = this.historyList
  4873. if (ArrayUtil.isEmpty(this.historyList)) {
  4874. ToastUtil.showToast('最近播放记录空空如也')
  4875. } else {
  4876. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  4877. }
  4878. this.isHistory = true
  4879. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4880. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  4881. this.titleBarModel.setTitleName('我的收藏')
  4882. this.currentTitleName = '我的收藏'
  4883. this.currentTitleCover = $r('app.media.ic_avatar1')
  4884. //加载动画效果
  4885. this.updateListData(this.favList)
  4886. if (ArrayUtil.isEmpty(this.favList)) {
  4887. ToastUtil.showToast('无音乐收藏记录')
  4888. } else {
  4889. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  4890. }
  4891. this.isFavMusic = true
  4892. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4893. } else {
  4894. this.currentTitleName = item.name
  4895. this.currentPath = item.filePath
  4896. this.currentTitleCover = $r('app.media.ic_avatar5')
  4897. this.getSortedFiles(this.currentPath)
  4898. }
  4899. //进入歌单的时候的滚动位置在顶部
  4900. if(this.twoFingerType==4){
  4901. setTimeout(() => {
  4902. this.waterScroller.scrollEdge(Edge.Top)
  4903. this.scroller.scrollEdge(Edge.Top)
  4904. }, 380)
  4905. }else{
  4906. if (this.isGridMusic) {
  4907. this.scroller.scrollEdge(Edge.Top)
  4908. }else{
  4909. this.listScroller.scrollEdge(Edge.Top)
  4910. }
  4911. }
  4912. break;
  4913. case CommonConstants.TYPE_IS_ARTIST:
  4914. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  4915. let offsetA = 0
  4916. if(this.twoFingerType==4){
  4917. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4918. let cur = this.waterScroller.currentOffset()
  4919. if (cur && typeof cur.yOffset === 'number') {
  4920. offsetA = cur.yOffset
  4921. }
  4922. }
  4923. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  4924. }else
  4925. if (this.isGridMusic) {
  4926. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4927. let cur = this.scroller.currentOffset()
  4928. if (cur && typeof cur.yOffset === 'number') {
  4929. offsetA = cur.yOffset
  4930. }
  4931. }
  4932. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  4933. } else {
  4934. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4935. let cur = this.listScroller.currentOffset()
  4936. if (cur && typeof cur.yOffset === 'number') {
  4937. offsetA = cur.yOffset
  4938. }
  4939. }
  4940. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  4941. }
  4942. let mList = this.artistMap.get(item.name)
  4943. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  4944. Utility.doSortListAscending(mList)
  4945. this.isCanBack = true
  4946. this.titleBarModel.setTitleName(item.name)
  4947. this.currentTitleName = '艺术家:' + item.name
  4948. if (item.pixelMapPath) {
  4949. this.currentTitleCover = item.pixelMapPath
  4950. }
  4951. this.updateListData(mList)
  4952. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4953. }
  4954. //进入歌单的时候的滚动位置在顶部
  4955. if(this.twoFingerType==4){
  4956. setTimeout(() => {
  4957. this.waterScroller.scrollEdge(Edge.Top)
  4958. this.scroller.scrollEdge(Edge.Top)
  4959. }, 380)
  4960. }else{
  4961. if (this.isGridMusic) {
  4962. this.scroller.scrollEdge(Edge.Top)
  4963. }else{
  4964. this.listScroller.scrollEdge(Edge.Top)
  4965. }
  4966. }
  4967. break;
  4968. case CommonConstants.TYPE_IS_ALBUM:
  4969. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  4970. let offset = 0
  4971. if(this.twoFingerType==4){
  4972. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4973. let cur = this.waterScroller.currentOffset()
  4974. if (cur && typeof cur.yOffset === 'number') {
  4975. offset = cur.yOffset
  4976. }
  4977. }
  4978. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  4979. }else
  4980. if (this.isGridMusic) {
  4981. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4982. let cur = this.scroller.currentOffset()
  4983. if (cur && typeof cur.yOffset === 'number') {
  4984. offset = cur.yOffset
  4985. }
  4986. }
  4987. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  4988. } else {
  4989. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4990. let cur = this.listScroller.currentOffset()
  4991. if (cur && typeof cur.yOffset === 'number') {
  4992. offset = cur.yOffset
  4993. }
  4994. }
  4995. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4996. }
  4997. let albumList = this.albumMap.get(item.name)
  4998. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4999. Utility.doSortListAscending(albumList)
  5000. this.isCanBack = true
  5001. this.titleBarModel.setTitleName(item.name)
  5002. this.currentTitleName = '专辑:' + item.name
  5003. if (item.pixelMapPath) {
  5004. this.currentTitleCover = item.pixelMapPath
  5005. }
  5006. this.updateListData(albumList)
  5007. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  5008. this.mScrollMap.set(item.name, this.selectedIndex)
  5009. }
  5010. //进入歌单的时候的滚动位置在顶部
  5011. if(this.twoFingerType==4){
  5012. setTimeout(() => {
  5013. this.waterScroller.scrollEdge(Edge.Top)
  5014. this.scroller.scrollEdge(Edge.Top)
  5015. }, 380)
  5016. }else{
  5017. if (this.isGridMusic) {
  5018. this.scroller.scrollEdge(Edge.Top)
  5019. }else{
  5020. this.listScroller.scrollEdge(Edge.Top)
  5021. }
  5022. }
  5023. break;
  5024. case CommonConstants.TYPE_IS_CSJAD:
  5025. return
  5026. break;
  5027. case CommonConstants.TYPE_LOCAL:
  5028. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  5029. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  5030. const cueTracks:CueTrack[] = cueinfo.tracks
  5031. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  5032. if(ArrayUtil.isNotEmpty(cueTracks)){
  5033. this.showCueDialog(cueTracks,cueinfo)
  5034. }
  5035. // this.showCueSheet = !this.showCueSheet
  5036. return
  5037. }
  5038. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5039. this.stop();
  5040. }
  5041. if (isOpen) {
  5042. this.currentSong = item
  5043. if (index !== undefined) {
  5044. this.curIndex = index
  5045. }
  5046. this.songList = []
  5047. this.songList.push(item)
  5048. this.sonDataSource.pushArrayData(this.songList)
  5049. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  5050. this.currentSong = item
  5051. if (index !== undefined) {
  5052. this.curIndex = index
  5053. }
  5054. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5055. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5056. }else {
  5057. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5058. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  5059. this.songList = globalVideoList
  5060. this.sonDataSource.pushArrayData(this.songList)
  5061. this.currentSong = globalVideoList[this.curIndex]
  5062. }
  5063. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5064. this.videoUrl = this.currentSong.filePath
  5065. this.name = this.currentSong.name
  5066. this.cover = this.currentSong.pixelMapPath
  5067. this.artist = this.currentSong.artist
  5068. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  5069. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  5070. this.startPlayOrResumePlay()
  5071. break;
  5072. case CommonConstants.TYPE_WEBDAV:
  5073. // 处理网络音频播放(WebDAV)
  5074. Logger.info(`heanup 处理网络音频播放: ${item.name}, URL: ${item.filePath}`)
  5075. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5076. this.stop();
  5077. }
  5078. if (isOpen) {
  5079. this.currentSong = item
  5080. if (index !== undefined) {
  5081. this.curIndex = index
  5082. }
  5083. this.songList = []
  5084. this.songList.push(item)
  5085. this.sonDataSource.pushArrayData(this.songList)
  5086. } else if (isFromSonPlayList) {
  5087. // 点击来自右下角的播放列表
  5088. this.currentSong = item
  5089. if (index !== undefined) {
  5090. this.curIndex = index
  5091. }
  5092. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5093. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5094. } else {
  5095. // 从全局网络音频列表中查找
  5096. let globalVideoList = this.videoLocalList.filter(video => video.type === CommonConstants.TYPE_WEBDAV) as VideoItem[];
  5097. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  5098. if (this.curIndex === -1 && index !== undefined) {
  5099. this.curIndex = index;
  5100. }
  5101. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  5102. this.currentSong = this.songList[this.curIndex];
  5103. this.sonDataSource.pushArrayData(this.songList)
  5104. }
  5105. AppStorage.setOrCreate('currentSong', this.currentSong);
  5106. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  5107. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  5108. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  5109. this.name = this.currentSong.name
  5110. this.cover = this.currentSong.pixelMapPath
  5111. this.artist = this.currentSong.artist
  5112. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  5113. this.startPlayOrResumePlay()
  5114. break;
  5115. }
  5116. }
  5117. private cueComponentId: number = 0
  5118. //显示cue分轨列表对话框
  5119. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  5120. this.getUIContext().getPromptAction().openCustomDialog({
  5121. builder: () => {
  5122. this.cueComptentBuilder(cueTracks,cueinfo)
  5123. },
  5124. isModal:true,
  5125. showInSubWindow:false,
  5126. maskColor: Color.Transparent,
  5127. dialogTransition: // 设置弹窗内容显示的过渡效果
  5128. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  5129. .animation({ duration: 600, curve: Curve.Smooth }),
  5130. maskTransition: // 设置蒙层显示的过渡效果
  5131. TransitionEffect.opacity(0.5)
  5132. .animation({ duration: 600, curve: Curve.Smooth })
  5133. }).then((dialogId: number) => {
  5134. this.cueComponentId = dialogId
  5135. })
  5136. .catch((error: BusinessError) => {
  5137. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5138. })
  5139. }
  5140. @Builder
  5141. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  5142. CueComptent({
  5143. title:cueinfo.title,
  5144. cueTracks:cueTracks,
  5145. isLongNameRoLL:this.isLongNameRoLL,
  5146. onCancel:()=>{
  5147. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  5148. },
  5149. onDoItemClick:(item: CueTrack, index: number)=>{
  5150. //获取cueinfo对应的filePath
  5151. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5152. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  5153. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  5154. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  5155. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  5156. if (this.currentSong){
  5157. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5158. this.stop();//播放之前先停止之前播放。
  5159. }
  5160. this.songList = globalVideoList
  5161. this.sonDataSource.pushArrayData(this.songList)
  5162. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  5163. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  5164. }else{
  5165. this.videoUrl = this.currentSong.filePath
  5166. }
  5167. this.name = item.title||this.currentSong.name
  5168. this.cover = this.currentSong.pixelMapPath
  5169. this.artist = item.performer||this.currentSong.artist
  5170. this.currentSong.name = this.name
  5171. this.currentSong.artist = this.artist
  5172. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5173. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  5174. }
  5175. }
  5176. })
  5177. }
  5178. @Builder
  5179. PlayController() {
  5180. Column() {
  5181. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  5182. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5183. Row() {
  5184. if(this.isHiCar()){
  5185. this.playConRigth()
  5186. Column(){
  5187. this.centerName()
  5188. }.layoutWeight(1)
  5189. .onClick(()=>{
  5190. this.showPlayerView()
  5191. })
  5192. this.playConLeft(false)
  5193. }else{
  5194. this.playConLeft()
  5195. this.playConRigth()
  5196. }
  5197. }
  5198. .width('100%')
  5199. .height(this.bottomBarHeight)
  5200. .justifyContent(FlexAlign.Center)
  5201. .hitTestBehavior(HitTestMode.Transparent)
  5202. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  5203. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  5204. // modalTransition: ModalTransition.DEFAULT,
  5205. transition: AnimationHelper.transitionInDown(666),
  5206. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  5207. })
  5208. .padding({
  5209. left: 16,
  5210. right: 16
  5211. })
  5212. Line()
  5213. .width('100%')
  5214. .height(25)
  5215. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  5216. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5217. }
  5218. .clickEffect({ level: ClickEffectLevel.HEAVY })
  5219. }
  5220. @State isFrontWhite: boolean = false
  5221. @Builder
  5222. centerName() {
  5223. Column() {
  5224. Text(this.currentSong?.name)
  5225. .fontSize(16)
  5226. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5227. .maxLines(1)
  5228. .fontColor($r('app.color.text_color'))
  5229. .fontWeight(500);
  5230. Row() {
  5231. Text(this.currentSong?.artist)
  5232. .margin({ top: 2 })
  5233. .fontSize(13)
  5234. .textAlign(TextAlign.Start)
  5235. .maxLines(1)
  5236. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5237. .fontColor($r('app.color.text_color'));
  5238. }
  5239. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5240. }
  5241. .alignItems(HorizontalAlign.Center)
  5242. }
  5243. @Builder
  5244. playConLeft(isLeft: boolean = true) {
  5245. Row() {
  5246. RotatingCover({ songLabel: this.currentSong?.pixelMapPath });
  5247. Column() {
  5248. Text(this.currentSong?.name)
  5249. .fontSize(16)
  5250. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5251. .maxLines(1)
  5252. .fontColor($r('app.color.text_color'))
  5253. .fontWeight(500);
  5254. Row() {
  5255. Text(this.currentSong?.artist)
  5256. .margin({ top: 2 })
  5257. .fontSize(13)
  5258. .textAlign(TextAlign.Start)
  5259. .maxLines(1)
  5260. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5261. .fontColor($r('app.color.text_color'));
  5262. }
  5263. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5264. }
  5265. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  5266. .margin({ right: isLeft?22:10 })
  5267. .visibility(isLeft? Visibility.Visible:Visibility.None)
  5268. }
  5269. .padding({ right: 18 })
  5270. .layoutWeight(isLeft?1:0)
  5271. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5272. .onClick(() => {
  5273. this.showPlayerView()
  5274. })
  5275. }
  5276. //打开播放页
  5277. showPlayerView() {
  5278. if (ArrayUtil.isNotEmpty(this.songList)) {
  5279. this.isShowPlay = true;
  5280. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  5281. this.initLyric(lyricPath);
  5282. this.startAutoHide();
  5283. } else {
  5284. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  5285. }
  5286. }
  5287. @Builder
  5288. playConRigth() {
  5289. Row() {
  5290. Image($r('app.media.hm_previous'))
  5291. .height(28)
  5292. .width(28)
  5293. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5294. .margin({ left: 8, right: 16 })
  5295. .fillColor(this.themeColor)
  5296. .displayPriority(2)
  5297. .onClick(() => {
  5298. if (ArrayUtil.isNotEmpty(this.songList)) {
  5299. this.playPrevious()
  5300. } else {
  5301. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5302. }
  5303. })
  5304. //播放进度条
  5305. Stack() {
  5306. Progress({
  5307. value: Math.floor(this.progressValue),
  5308. type: ProgressType.Ring,
  5309. })
  5310. .color(this.themeColor)// 进度条前景色为灰色
  5311. .backgroundColor($r('app.color.index_background'))
  5312. .height(40)
  5313. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5314. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  5315. .height(38)
  5316. .width(38)
  5317. .displayPriority(3)
  5318. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5319. .fillColor(this.themeColor)
  5320. .onClick(() => {
  5321. if (ArrayUtil.isNotEmpty(this.songList)) {
  5322. console.info('onecold playOrPause 4642')
  5323. this.playOrPause()
  5324. } else {
  5325. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5326. }
  5327. })
  5328. }
  5329. Image($r('app.media.hm_next'))
  5330. .height(28)
  5331. .width(28)
  5332. .margin({
  5333. right: 16,
  5334. left: 16
  5335. })
  5336. .fillColor(this.themeColor)
  5337. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5338. .displayPriority(2)
  5339. .onClick(() => {
  5340. if (ArrayUtil.isNotEmpty(this.songList)) {
  5341. this.playNext()
  5342. } else {
  5343. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5344. }
  5345. })
  5346. Image($r('app.media.hm_playlist'))
  5347. .height(28)
  5348. .width(28)
  5349. .displayPriority(1)
  5350. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5351. .fillColor(this.themeColor)
  5352. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  5353. height: '95%',
  5354. dragBar: true,
  5355. showClose: true,
  5356. blurStyle: BlurStyle.Thin,
  5357. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5358. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  5359. title: {
  5360. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5361. + `(${this.songList.length}首)`
  5362. }
  5363. })
  5364. .onClick(() => {
  5365. if (ArrayUtil.isNotEmpty(this.songList)) {
  5366. this.isShowSheet = !this.isShowSheet;
  5367. this.isFrontWhite = false
  5368. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  5369. this.scrollIndex()
  5370. } else {
  5371. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5372. }
  5373. })
  5374. }
  5375. }
  5376. scrollIndex(){
  5377. try {
  5378. setTimeout(() => {
  5379. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  5380. if(this.curIndex>60){
  5381. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  5382. }else{
  5383. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5384. }
  5385. })
  5386. }, 123)
  5387. }catch (error) {
  5388. console.error(`onecold scrollIndex出错: ${error}`);
  5389. }
  5390. }
  5391. //播放列表布局
  5392. @Builder
  5393. PlayListSheet() {
  5394. Column() {
  5395. this.PlayList()
  5396. }
  5397. .width('100%')
  5398. .height('100%')
  5399. }
  5400. @State titleStr: string = ''
  5401. @State ablumStr: string = ''
  5402. @State artistStr: string = ''
  5403. @State lyricConStr: string = ''
  5404. @State currentEditItem: string = ''
  5405. @State yearStr: string = ''
  5406. @State trackStr: string = ''
  5407. @State genreStr: string = ''
  5408. @State imagePathStr: string = ''
  5409. @State albumArtistStr: string = ''
  5410. @State composerStr: string = ''
  5411. @State lyricistStr: string = ''
  5412. @State commentStr: string = ''
  5413. @State discStr: string = ''
  5414. doUpdateData() {
  5415. setTimeout(() => {
  5416. if (this.modeType === 0) {
  5417. this.deleteCache(this.currentPath)
  5418. this.getSortedFiles(this.currentPath)
  5419. }
  5420. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5421. workerInstance.postMessage({ code: 3, data: this.context });
  5422. workerInstance.postMessage({ code: 4, data: this.context });
  5423. }, 999)
  5424. }
  5425. //编辑信息
  5426. async doEdit(item: VideoItem) {
  5427. if (!item) {
  5428. return
  5429. }
  5430. if (StrUtil.isEmpty(this.titleStr)) {
  5431. ToastUtil.showToast('标题不能为空')
  5432. return
  5433. }
  5434. //用户更改了封面,那就内嵌下封面
  5435. if(StrUtil.isNotEmpty(this.imagePathStr)){
  5436. const resultCover:boolean = await changeMusicCover(this.context,
  5437. item.filePath,this.imagePathStr,true);
  5438. this.imagePathStr = ''
  5439. if(resultCover){
  5440. ToastUtil.showToast('内嵌封面成功')
  5441. }
  5442. }
  5443. const metadata:FFMpegTags = {
  5444. title: this.titleStr,
  5445. artist: this.artistStr,
  5446. album: this.ablumStr,
  5447. TYER:this.yearStr,
  5448. genre:this.genreStr,
  5449. track:this.trackStr,
  5450. album_artist:this.albumArtistStr,
  5451. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  5452. COMPOSER:this.composerStr,
  5453. lyricist:this.lyricistStr,
  5454. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  5455. comment:this.commentStr,
  5456. disc:this.discStr,
  5457. };
  5458. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  5459. const result:boolean = await repairAudioMetadata(
  5460. item.filePath,
  5461. this.lyricConStr,
  5462. metadata,
  5463. true
  5464. );
  5465. if (result) {
  5466. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  5467. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  5468. (success: boolean, error?: string) => {
  5469. // this.isShowEdit = false
  5470. if (success) {
  5471. console.log(" onecold 编辑信息成功,数据库已同步");
  5472. ToastUtil.showToast('内嵌音乐标签成功')
  5473. this.isShowMoreView = false
  5474. this.name = this.titleStr
  5475. if (item.filePath == this.currentSong?.filePath) {
  5476. this.currentSong.name = this.titleStr
  5477. this.artist = this.artistStr
  5478. this.currentSong.artist = this.artistStr
  5479. this.currentSong.album = this.ablumStr
  5480. this.currentSong.year = this.yearStr
  5481. this.currentSong.genre = this.genreStr
  5482. this.currentSong.track = this.trackStr
  5483. this.currentSong.lyricContent = this.lyricConStr
  5484. this.initLyric(item.filePath)
  5485. this.currentSong.ALBUMARTIST = this.albumArtistStr
  5486. this.currentSong.COMPOSER = this.composerStr
  5487. this.currentSong.LYRICIST = this.lyricistStr
  5488. this.currentSong.COMMENT = this.commentStr
  5489. }
  5490. this.doUpdateData()
  5491. } else {
  5492. // ToastUtil.showToast('保存失败' + error?.toString())
  5493. console.error(" onecold 编辑信息数据库失败原因: " + error);
  5494. }
  5495. });
  5496. console.log(' onecold 元数据标签更新成功,');
  5497. } else {
  5498. ToastUtil.showToast('内嵌音乐标签失败')
  5499. console.log('onecold 内嵌音乐标签失败');
  5500. }
  5501. this.longItemFilePath = ''
  5502. this.tempLyricContent = ''
  5503. this.isShowEdit = false
  5504. }
  5505. updateLyricToDB() {
  5506. }
  5507. @Builder
  5508. editSheet(item: VideoItem) {
  5509. Scroll() {
  5510. Column() {
  5511. this.editDetail(item)
  5512. }
  5513. }
  5514. .width('100%')
  5515. .height('100%')
  5516. }
  5517. @Builder
  5518. editDetail(item: VideoItem) {
  5519. Column() {
  5520. if (item) {
  5521. Row() {
  5522. Stack() {
  5523. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  5524. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  5525. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  5526. item.pixelMapPath)
  5527. .fillColor(this.themeColor)
  5528. .height(88)
  5529. .width(88)
  5530. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5531. .borderRadius(12)
  5532. .clip(true)
  5533. .opacity(this.opacityItem)// 绑定透明度
  5534. .margin({ left: 25 })
  5535. }
  5536. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5537. .onClick(async () => {
  5538. const imagePath:string | undefined = await this.goSelectImage(item);
  5539. if (imagePath) {
  5540. //用户更改过图片
  5541. this.imagePathStr = imagePath
  5542. }
  5543. })
  5544. .width('28%')
  5545. Row() {
  5546. Column() {
  5547. Text(item.name)
  5548. .fontSize(17)
  5549. .maxLines(1)
  5550. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5551. .animation({
  5552. duration: 555,
  5553. curve: 'Linear',
  5554. })
  5555. .fontColor(this.themeColor)
  5556. .margin({ left: 8 })
  5557. Row() {
  5558. Text(item.artist)
  5559. .fontSize(14)
  5560. .maxLines(1)
  5561. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5562. .padding({ top: 8 })
  5563. .fontColor(this.themeColor)
  5564. .margin({ left: 8 })
  5565. }
  5566. }
  5567. .height('100%')
  5568. .width(100)
  5569. .layoutWeight(1)
  5570. .justifyContent(FlexAlign.Center)
  5571. .alignItems(HorizontalAlign.Start)
  5572. Column() {
  5573. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5574. Row(){
  5575. SymbolGlyph($r('sys.symbol.picture'))
  5576. .fontSize(18)
  5577. .fontColor([Color.White])
  5578. Text('获取封面')
  5579. .margin({ left: 4 })
  5580. .fontSize(11)
  5581. .fontColor(Color.White)
  5582. .fontWeight(480)
  5583. .textAlign(TextAlign.Center)
  5584. }
  5585. .justifyContent(FlexAlign.Center)
  5586. }
  5587. .height(38)
  5588. .width(100)
  5589. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5590. .backgroundColor(this.themeColor)
  5591. .stateEffect(true)
  5592. .margin({ right: 35 })
  5593. .onClick(async () => {
  5594. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  5595. this.showTipsDialog();
  5596. return; // Return empty string when no API is configured
  5597. }
  5598. const imagePath:string | undefined = await this.doSearchCover(item);
  5599. console.info('onecold imagePath = '+imagePath)
  5600. if (StrUtil.isNotEmpty(imagePath)) {
  5601. //用户更改过图片
  5602. this.imagePathStr = imagePath
  5603. ToastUtil.showToast('获取封面成功')
  5604. }else{
  5605. ToastUtil.showToast('获取封面失败,请重试')
  5606. }
  5607. })
  5608. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5609. Row(){
  5610. SymbolGlyph($r('sys.symbol.input_mode'))
  5611. .fontSize(18)
  5612. .fontColor([Color.White])
  5613. Text('获取歌词')
  5614. .margin({ left: 4 })
  5615. .fontSize(11)
  5616. .fontColor(Color.White)
  5617. .fontWeight(480)
  5618. .textAlign(TextAlign.Center)
  5619. }
  5620. .justifyContent(FlexAlign.Center)
  5621. }
  5622. .height(38)
  5623. .width(100)
  5624. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5625. .backgroundColor(this.themeColor)
  5626. .stateEffect(true)
  5627. .margin({ top: 9, right: 35 })
  5628. .onClick(async () => {
  5629. //判断有没有设置api
  5630. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  5631. if (StrUtil.isEmpty(apiUrl)) {
  5632. this.isLyricSetting = false
  5633. this.showTipsDialog()
  5634. return
  5635. }
  5636. let artist = item.artist
  5637. let title = item.name
  5638. if(!artist)
  5639. artist = ''
  5640. if(!title)
  5641. title = ''
  5642. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  5643. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5644. this.lyricConStr = res;
  5645. ToastUtil.showToast('获取歌词成功')
  5646. }else{
  5647. ToastUtil.showToast('获取歌词失败,请重试')
  5648. }
  5649. })
  5650. }
  5651. .justifyContent(FlexAlign.Start)
  5652. }
  5653. .height('100%')
  5654. .justifyContent(FlexAlign.Start)
  5655. .layoutWeight(1)
  5656. }
  5657. .width('100%')
  5658. .height(98)
  5659. Row() {
  5660. Text('标题:')
  5661. .fontSize(14)
  5662. .fontColor($r('app.color.text_color'))
  5663. .margin({ left: 22 })
  5664. TextInput({ text: item.name })
  5665. .height(40)
  5666. .maxLines(1)
  5667. .fontSize(14)
  5668. .layoutWeight(1)
  5669. .fontColor($r('app.color.text_color'))
  5670. .margin({ right: 20, left: 10 })
  5671. .onChange((val: string) => {
  5672. this.titleStr = val
  5673. })
  5674. }
  5675. .width('100%')
  5676. .margin({ top: 10, bottom: 10 })
  5677. .justifyContent(FlexAlign.Start)
  5678. Row() {
  5679. Text('艺术家:')
  5680. .fontSize(14)
  5681. .fontColor($r('app.color.text_color'))
  5682. .margin({ left: 22 })
  5683. TextInput({ text: item.artist })
  5684. .height(40)
  5685. .maxLines(1)
  5686. .fontSize(14)
  5687. .layoutWeight(1)
  5688. .fontColor($r('app.color.text_color'))
  5689. .margin({ right: 20, left: 10 })
  5690. .onChange((val: string) => {
  5691. this.artistStr = val
  5692. })
  5693. }
  5694. .width('100%')
  5695. .margin({ top: 10, bottom: 10 })
  5696. .justifyContent(FlexAlign.Start)
  5697. Row() {
  5698. Text('专辑名:')
  5699. .fontSize(14)
  5700. .fontColor($r('app.color.text_color'))
  5701. .margin({ left: 22 })
  5702. TextInput({ text: item.album })
  5703. .height(40)
  5704. .maxLines(1)
  5705. .fontSize(14)
  5706. .layoutWeight(1)
  5707. .fontColor($r('app.color.text_color'))
  5708. .margin({ right: 20, left: 10 })
  5709. .onChange((val: string) => {
  5710. this.ablumStr = val
  5711. })
  5712. }
  5713. .width('100%')
  5714. .margin({ top: 10, bottom: 10 })
  5715. .justifyContent(FlexAlign.Start)
  5716. Row() {
  5717. Column(){
  5718. Column(){
  5719. Text('歌词:')
  5720. .fontSize(14)
  5721. .fontColor($r('app.color.text_color'))
  5722. .margin({ top:9,left: 22 })
  5723. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5724. SymbolGlyph($r('sys.symbol.trash_fill'))
  5725. .fontSize(25)
  5726. .alignSelf(ItemAlign.Center)
  5727. .margin({ left: 22,top:25})
  5728. }
  5729. .backgroundColor(Color.Transparent)
  5730. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5731. Visibility.None:Visibility.Visible)
  5732. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5733. .onClick(()=>{
  5734. this.lyricConStr = ''
  5735. this.lyricContent = ''
  5736. this.tempLyricContent = ''
  5737. })
  5738. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5739. SymbolGlyph($r('sys.symbol.plus'))
  5740. .fontSize(25)
  5741. .alignSelf(ItemAlign.Center)
  5742. .margin({ left: 22,top:25})
  5743. }
  5744. .backgroundColor(Color.Transparent)
  5745. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5746. .onClick( ()=>{
  5747. this.callFilePickerSelectFileForLyric()
  5748. })
  5749. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5750. SymbolGlyph($r('sys.symbol.traditional_square'))
  5751. .fontSize(25)
  5752. .alignSelf(ItemAlign.Center)
  5753. .margin({ left: 22,top:25})
  5754. }
  5755. .backgroundColor(Color.Transparent)
  5756. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5757. Visibility.None:Visibility.Visible)
  5758. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5759. .onClick( ()=>{
  5760. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5761. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  5762. })
  5763. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5764. Image($r('app.media.jianti'))
  5765. .height(25)
  5766. .fillColor($r('app.color.text_color'))
  5767. .alignSelf(ItemAlign.Center)
  5768. .margin({ left: 22,top:25})
  5769. }
  5770. .backgroundColor(Color.Transparent)
  5771. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5772. Visibility.None:Visibility.Visible)
  5773. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5774. .onClick( ()=>{
  5775. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5776. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  5777. })
  5778. }
  5779. .layoutWeight(1)
  5780. }
  5781. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  5782. this.tempLyricContent })
  5783. .type(TextAreaType.NORMAL)
  5784. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  5785. .fontSize(14)
  5786. .layoutWeight(1)
  5787. .fontColor($r('app.color.text_color'))
  5788. .margin({ right: 20, left: 10 })
  5789. .onChange((val: string) => {
  5790. this.lyricConStr = val
  5791. })
  5792. }
  5793. .width('100%')
  5794. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  5795. .margin({ top: 10, bottom: 10 })
  5796. .justifyContent(FlexAlign.Start)
  5797. Row() {
  5798. Text('年份:')
  5799. .fontSize(14)
  5800. .fontColor($r('app.color.text_color'))
  5801. .margin({ left: 22 })
  5802. TextInput({ text: item.year })
  5803. .height(40)
  5804. .maxLines(1)
  5805. .fontSize(14)
  5806. .type(InputType.Number)
  5807. .layoutWeight(1)
  5808. .fontColor($r('app.color.text_color'))
  5809. .margin({ right: 20, left: 10 })
  5810. .onChange((val: string) => {
  5811. this.yearStr = val
  5812. })
  5813. }
  5814. .width('100%')
  5815. .margin({ top: 10, bottom: 10 })
  5816. .justifyContent(FlexAlign.Start)
  5817. Row() {
  5818. Text('音轨号:')
  5819. .fontSize(14)
  5820. .fontColor($r('app.color.text_color'))
  5821. .margin({ left: 22 })
  5822. TextInput({ text:item.track=='未知'?'': item.track })
  5823. .height(40)
  5824. .maxLines(1)
  5825. .fontSize(14)
  5826. .type(InputType.Number)
  5827. .layoutWeight(1)
  5828. .fontColor($r('app.color.text_color'))
  5829. .margin({ right: 20, left: 10 })
  5830. .onChange((val: string) => {
  5831. this.trackStr = val
  5832. })
  5833. }
  5834. .width('100%')
  5835. .margin({ top: 10, bottom: 10 })
  5836. .justifyContent(FlexAlign.Start)
  5837. Row() {
  5838. Text('碟号:')
  5839. .fontSize(14)
  5840. .fontColor($r('app.color.text_color'))
  5841. .margin({ left: 22 })
  5842. TextInput({ text:item.disc })
  5843. .height(40)
  5844. .maxLines(1)
  5845. .fontSize(14)
  5846. .type(InputType.Number)
  5847. .layoutWeight(1)
  5848. .fontColor($r('app.color.text_color'))
  5849. .margin({ right: 20, left: 10 })
  5850. .onChange((val: string) => {
  5851. this.discStr = val
  5852. })
  5853. }
  5854. .width('100%')
  5855. .margin({ top: 10, bottom: 10 })
  5856. .justifyContent(FlexAlign.Start)
  5857. Row() {
  5858. Text('风格:')
  5859. .fontSize(14)
  5860. .fontColor($r('app.color.text_color'))
  5861. .margin({ left: 22 })
  5862. TextInput({ text: item.genre })
  5863. .height(40)
  5864. .maxLines(1)
  5865. .fontSize(14)
  5866. .layoutWeight(1)
  5867. .fontColor($r('app.color.text_color'))
  5868. .margin({ right: 20, left: 10 })
  5869. .onChange((val: string) => {
  5870. this.genreStr = val
  5871. })
  5872. }
  5873. .width('100%')
  5874. .margin({ top: 10, bottom: 10 })
  5875. .justifyContent(FlexAlign.Start)
  5876. Row() {
  5877. Text('专辑艺术家:')
  5878. .fontSize(14)
  5879. .fontColor($r('app.color.text_color'))
  5880. .margin({ left: 22 })
  5881. TextInput({ text: item.ALBUMARTIST })
  5882. .height(40)
  5883. .maxLines(1)
  5884. .fontSize(14)
  5885. .layoutWeight(1)
  5886. .fontColor($r('app.color.text_color'))
  5887. .margin({ right: 20, left: 10 })
  5888. .onChange((val: string) => {
  5889. this.albumArtistStr = val
  5890. })
  5891. }
  5892. .width('100%')
  5893. .margin({ top: 10, bottom: 10 })
  5894. .justifyContent(FlexAlign.Start)
  5895. Row() {
  5896. Text('作曲:')
  5897. .fontSize(14)
  5898. .fontColor($r('app.color.text_color'))
  5899. .margin({ left: 22 })
  5900. TextInput({ text: item.COMPOSER })
  5901. .height(40)
  5902. .maxLines(1)
  5903. .fontSize(14)
  5904. .layoutWeight(1)
  5905. .fontColor($r('app.color.text_color'))
  5906. .margin({ right: 20, left: 10 })
  5907. .onChange((val: string) => {
  5908. this.composerStr = val
  5909. })
  5910. }
  5911. .width('100%')
  5912. .margin({ top: 10, bottom: 10 })
  5913. .justifyContent(FlexAlign.Start)
  5914. Row() {
  5915. Text('作词:')
  5916. .fontSize(14)
  5917. .fontColor($r('app.color.text_color'))
  5918. .margin({ left: 22 })
  5919. TextInput({ text: item.LYRICIST })
  5920. .height(40)
  5921. .maxLines(1)
  5922. .fontSize(14)
  5923. .layoutWeight(1)
  5924. .fontColor($r('app.color.text_color'))
  5925. .margin({ right: 20, left: 10 })
  5926. .onChange((val: string) => {
  5927. this.lyricistStr = val
  5928. })
  5929. }
  5930. .width('100%')
  5931. .margin({ top: 10, bottom: 10 })
  5932. .justifyContent(FlexAlign.Start)
  5933. Row() {
  5934. Text('注释:')
  5935. .fontSize(14)
  5936. .fontColor($r('app.color.text_color'))
  5937. .margin({ left: 22 })
  5938. TextInput({ text: item.COMMENT })
  5939. .height(40)
  5940. .maxLines(1)
  5941. .fontSize(14)
  5942. .layoutWeight(1)
  5943. .fontColor($r('app.color.text_color'))
  5944. .margin({ right: 20, left: 10 })
  5945. .onChange((val: string) => {
  5946. this.commentStr = val
  5947. })
  5948. }
  5949. .width('100%')
  5950. .margin({ top: 10, bottom: 10 })
  5951. .justifyContent(FlexAlign.Start)
  5952. Row() {
  5953. Button('保存')
  5954. .fontColor(Color.White)
  5955. .layoutWeight(1)
  5956. .height(50)
  5957. .width(100)
  5958. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5959. .backgroundColor(this.themeColor)
  5960. .stateEffect(true)
  5961. .margin({ right: 20, bottom: 20 })
  5962. .onClick(async () => {
  5963. this.doEdit(item)
  5964. })
  5965. Button('取消')
  5966. .fontColor(Color.White)
  5967. .layoutWeight(1)
  5968. .height(50)
  5969. .width(100)
  5970. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5971. .backgroundColor(this.themeColor)
  5972. .stateEffect(true)
  5973. .margin({ left: 20, bottom: 20 })
  5974. .onClick(async () => {
  5975. if(this.isGridMusic){
  5976. this.longItemFilePath =''
  5977. }else{
  5978. this.isShowEdit = false
  5979. }
  5980. this.setEditStrEmpty()
  5981. if(this.isShowPlay){
  5982. this.isShowEdit = false
  5983. }
  5984. })
  5985. }
  5986. .margin({
  5987. left: 38,
  5988. right: 38,
  5989. top: 10,
  5990. bottom: 10
  5991. })
  5992. .width(250)
  5993. .height(60)
  5994. }
  5995. }
  5996. .margin({ bottom: 20 })
  5997. }
  5998. setEditStrEmpty(){
  5999. this.imagePathStr = ''
  6000. this.lyricConStr = ''
  6001. this.artistStr = ''
  6002. this.titleStr = ''
  6003. this.ablumStr = ''
  6004. this.genreStr = ''
  6005. this.yearStr = ''
  6006. this.trackStr = ''
  6007. this.albumArtistStr = ''
  6008. this.composerStr = ''
  6009. this.lyricistStr = ''
  6010. this.commentStr = ''
  6011. this.discStr = ''
  6012. }
  6013. @Builder
  6014. detailSheet(item:VideoItem) {
  6015. Scroll() {
  6016. Column() {
  6017. this.songDetail(item)
  6018. }
  6019. }
  6020. .width('100%')
  6021. .height('100%')
  6022. }
  6023. @Builder
  6024. songDetail(currentItem:VideoItem) {
  6025. Column() {
  6026. if (currentItem) {
  6027. Row() {
  6028. Stack() {
  6029. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  6030. currentItem.pixelMapPath)
  6031. .fillColor(this.themeColor)
  6032. .height(80)
  6033. .width(80)
  6034. .borderRadius(10)
  6035. .opacity(this.opacityItem)// 绑定透明度
  6036. .margin({ left: 22 })
  6037. }
  6038. Column() {
  6039. Column() {
  6040. Text(currentItem.name)
  6041. .fontSize(16)
  6042. .maxLines(1)
  6043. .animation({
  6044. duration: 555,
  6045. curve: 'Linear',
  6046. })
  6047. .fontColor($r('app.color.text_color'))
  6048. .margin({ left: 15 })
  6049. }
  6050. .height('100%')
  6051. .width('100%')
  6052. .justifyContent(FlexAlign.Center)
  6053. .alignItems(HorizontalAlign.Start)
  6054. }
  6055. .height('100%')
  6056. }
  6057. .width('100%')
  6058. .height(90)
  6059. .justifyContent(FlexAlign.SpaceBetween)
  6060. Row() {
  6061. Text('艺术家:')
  6062. .fontSize(14)
  6063. .fontColor($r('app.color.text_color'))
  6064. .margin({ left: 22 })
  6065. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  6066. .fontSize(14)
  6067. .fontColor($r('app.color.text_color'))
  6068. .margin({ left: 10 })
  6069. .layoutWeight(1)
  6070. }
  6071. .width('100%')
  6072. .margin({ top: 10, bottom: 10 })
  6073. .justifyContent(FlexAlign.Start)
  6074. Row() {
  6075. Text('专辑名:')
  6076. .fontSize(14)
  6077. .fontColor($r('app.color.text_color'))
  6078. .margin({ left: 22 })
  6079. Text(currentItem?.album ?currentItem.album : '未知专辑')
  6080. .fontSize(14)
  6081. .margin({ left: 10 })
  6082. .fontColor($r('app.color.text_color'))
  6083. .layoutWeight(1)
  6084. }
  6085. .width('100%')
  6086. .margin({ top: 10, bottom: 10 })
  6087. .justifyContent(FlexAlign.Start)
  6088. Row() {
  6089. Text('时长:')
  6090. .fontSize(14)
  6091. .fontColor($r('app.color.text_color'))
  6092. .margin({ left: 22 })
  6093. Text(StrUtil.isEmpty(currentItem.duration)?
  6094. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  6095. .fontSize(14)
  6096. .margin({ left: 10 })
  6097. .fontColor($r('app.color.text_color'))
  6098. .layoutWeight(1)
  6099. }
  6100. .width('100%')
  6101. .margin({ top: 10, bottom: 10 })
  6102. .justifyContent(FlexAlign.Start)
  6103. Row() {
  6104. Text('采样率:')
  6105. .fontSize(14)
  6106. .fontColor($r('app.color.text_color'))
  6107. .margin({ left: 22 })
  6108. Text(Utility.convertToKHz(currentItem.sampleRate))
  6109. .fontSize(14)
  6110. .margin({ left: 10 })
  6111. .fontColor($r('app.color.text_color'))
  6112. .layoutWeight(1)
  6113. }
  6114. .width('100%')
  6115. .margin({ top: 10, bottom: 10 })
  6116. .justifyContent(FlexAlign.Start)
  6117. Row() {
  6118. Text('比特率:')
  6119. .fontSize(14)
  6120. .fontColor($r('app.color.text_color'))
  6121. .margin({ left: 22 })
  6122. Text(currentItem.bit_rate)
  6123. .fontSize(14)
  6124. .margin({ left: 10 })
  6125. .fontColor($r('app.color.text_color'))
  6126. .layoutWeight(1)
  6127. }
  6128. .width('100%')
  6129. .margin({ top: 10, bottom: 10 })
  6130. .justifyContent(FlexAlign.Start)
  6131. Row() {
  6132. Text('位深:')
  6133. .fontSize(14)
  6134. .fontColor($r('app.color.text_color'))
  6135. .margin({ left: 22 })
  6136. Text(`${currentItem.bits_per_raw_sample} bits`)
  6137. .fontSize(14)
  6138. .margin({ left: 10 })
  6139. .fontColor($r('app.color.text_color'))
  6140. .layoutWeight(1)
  6141. }
  6142. .width('100%')
  6143. .margin({ top: 10, bottom: 10 })
  6144. .justifyContent(FlexAlign.Start)
  6145. Row() {
  6146. Text('声道:')
  6147. .fontSize(14)
  6148. .fontColor($r('app.color.text_color'))
  6149. .margin({ left: 22 })
  6150. Text(`${currentItem.channels}`)
  6151. .fontSize(14)
  6152. .margin({ left: 10 })
  6153. .fontColor($r('app.color.text_color'))
  6154. .layoutWeight(1)
  6155. }
  6156. .width('100%')
  6157. .margin({ top: 10, bottom: 10 })
  6158. .justifyContent(FlexAlign.Start)
  6159. Row() {
  6160. Text('声道布局:')
  6161. .fontSize(14)
  6162. .fontColor($r('app.color.text_color'))
  6163. .margin({ left: 22 })
  6164. Text(`${currentItem.channel_layout}`)
  6165. .fontSize(14)
  6166. .margin({ left: 10 })
  6167. .fontColor($r('app.color.text_color'))
  6168. .layoutWeight(1)
  6169. }
  6170. .width('100%')
  6171. .margin({ top: 10, bottom: 10 })
  6172. .justifyContent(FlexAlign.Start)
  6173. Row() {
  6174. Text('起始播放点:')
  6175. .fontSize(14)
  6176. .fontColor($r('app.color.text_color'))
  6177. .margin({ left: 22 })
  6178. Text(`${currentItem.start_time}`)
  6179. .fontSize(14)
  6180. .margin({ left: 10 })
  6181. .fontColor($r('app.color.text_color'))
  6182. .layoutWeight(1)
  6183. }
  6184. .width('100%')
  6185. .margin({ top: 10, bottom: 10 })
  6186. .justifyContent(FlexAlign.Start)
  6187. Row() {
  6188. Text('风格:')
  6189. .fontSize(14)
  6190. .fontColor($r('app.color.text_color'))
  6191. .margin({ left: 22 })
  6192. Text(currentItem.genre)
  6193. .fontSize(14)
  6194. .margin({ left: 10 })
  6195. .fontColor($r('app.color.text_color'))
  6196. .layoutWeight(1)
  6197. }
  6198. .width('100%')
  6199. .margin({ top: 10, bottom: 10 })
  6200. .justifyContent(FlexAlign.Start)
  6201. Row() {
  6202. Text('发行时间:')
  6203. .fontSize(14)
  6204. .fontColor($r('app.color.text_color'))
  6205. .margin({ left: 22 })
  6206. Text(currentItem.year)
  6207. .fontSize(14)
  6208. .margin({ left: 10 })
  6209. .fontColor($r('app.color.text_color'))
  6210. .layoutWeight(1)
  6211. }
  6212. .width('100%')
  6213. .margin({ top: 10, bottom: 10 })
  6214. .justifyContent(FlexAlign.Start)
  6215. Row() {
  6216. Text('质量评分:')
  6217. .fontSize(14)
  6218. .fontColor($r('app.color.text_color'))
  6219. .margin({ left: 22 })
  6220. Text(currentItem.probe_score+"")
  6221. .fontSize(14)
  6222. .margin({ left: 10 })
  6223. .fontColor($r('app.color.text_color'))
  6224. .layoutWeight(1)
  6225. }
  6226. .width('100%')
  6227. .margin({ top: 10, bottom: 10 })
  6228. .justifyContent(FlexAlign.Start)
  6229. Row() {
  6230. Text('音轨号:')
  6231. .fontSize(14)
  6232. .fontColor($r('app.color.text_color'))
  6233. .margin({ left: 22 })
  6234. Text(currentItem.track)
  6235. .fontSize(14)
  6236. .margin({ left: 10 })
  6237. .fontColor($r('app.color.text_color'))
  6238. .layoutWeight(1)
  6239. }
  6240. .width('100%')
  6241. .margin({ top: 10, bottom: 10 })
  6242. .justifyContent(FlexAlign.Start)
  6243. Row() {
  6244. Text('碟号:')
  6245. .fontSize(14)
  6246. .fontColor($r('app.color.text_color'))
  6247. .margin({ left: 22 })
  6248. Text(currentItem.disc)
  6249. .fontSize(14)
  6250. .margin({ left: 10 })
  6251. .fontColor($r('app.color.text_color'))
  6252. .layoutWeight(1)
  6253. }
  6254. .width('100%')
  6255. .margin({ top: 10, bottom: 10 })
  6256. .justifyContent(FlexAlign.Start)
  6257. Row() {
  6258. Text('专辑艺术家:')
  6259. .fontSize(14)
  6260. .fontColor($r('app.color.text_color'))
  6261. .margin({ left: 22 })
  6262. Text(currentItem.ALBUMARTIST)
  6263. .fontSize(14)
  6264. .margin({ left: 10 })
  6265. .fontColor($r('app.color.text_color'))
  6266. .layoutWeight(1)
  6267. }
  6268. .width('100%')
  6269. .margin({ top: 10, bottom: 10 })
  6270. .justifyContent(FlexAlign.Start)
  6271. Row() {
  6272. Text('作曲家:')
  6273. .fontSize(14)
  6274. .fontColor($r('app.color.text_color'))
  6275. .margin({ left: 22 })
  6276. Text(currentItem.COMPOSER)
  6277. .fontSize(14)
  6278. .margin({ left: 10 })
  6279. .fontColor($r('app.color.text_color'))
  6280. .layoutWeight(1)
  6281. }
  6282. .width('100%')
  6283. .margin({ top: 10, bottom: 10 })
  6284. .justifyContent(FlexAlign.Start)
  6285. Row() {
  6286. Text('作词家:')
  6287. .fontSize(14)
  6288. .fontColor($r('app.color.text_color'))
  6289. .margin({ left: 22 })
  6290. Text(currentItem.LYRICIST)
  6291. .fontSize(14)
  6292. .margin({ left: 10 })
  6293. .fontColor($r('app.color.text_color'))
  6294. .layoutWeight(1)
  6295. }
  6296. .width('100%')
  6297. .margin({ top: 10, bottom: 10 })
  6298. .justifyContent(FlexAlign.Start)
  6299. Row() {
  6300. Text('注释:')
  6301. .fontSize(14)
  6302. .fontColor($r('app.color.text_color'))
  6303. .margin({ left: 22 })
  6304. Text(currentItem.COMMENT)
  6305. .fontSize(14)
  6306. .margin({ left: 10 })
  6307. .fontColor($r('app.color.text_color'))
  6308. .layoutWeight(1)
  6309. }
  6310. .width('100%')
  6311. .margin({ top: 10, bottom: 10 })
  6312. .justifyContent(FlexAlign.Start)
  6313. Row() {
  6314. Text('格式:')
  6315. .fontSize(14)
  6316. .fontColor($r('app.color.text_color'))
  6317. .margin({ left: 22 })
  6318. Text(Utility.formatMimeType(currentItem.mimeType))
  6319. .fontSize(14)
  6320. .margin({ left: 10 })
  6321. .fontColor($r('app.color.text_color'))
  6322. .layoutWeight(1)
  6323. }
  6324. .width('100%')
  6325. .margin({ top: 10, bottom: 10 })
  6326. .justifyContent(FlexAlign.Start)
  6327. Row() {
  6328. Text('播放次数:')
  6329. .fontSize(14)
  6330. .fontColor($r('app.color.text_color'))
  6331. .margin({ left: 22 })
  6332. Text(currentItem.playCount?.toString())
  6333. .fontSize(14)
  6334. .margin({ left: 10 })
  6335. .fontColor($r('app.color.text_color'))
  6336. .layoutWeight(1)
  6337. }
  6338. .width('100%')
  6339. .margin({ top: 10, bottom: 10 })
  6340. .justifyContent(FlexAlign.Start)
  6341. Row() {
  6342. Text('流数量:')
  6343. .fontSize(14)
  6344. .fontColor($r('app.color.text_color'))
  6345. .margin({ left: 22 })
  6346. Text(currentItem.nb_streams?.toString())
  6347. .fontSize(14)
  6348. .margin({ left: 10 })
  6349. .fontColor($r('app.color.text_color'))
  6350. .layoutWeight(1)
  6351. }
  6352. .width('100%')
  6353. .margin({ top: 10, bottom: 10 })
  6354. .justifyContent(FlexAlign.Start)
  6355. Row() {
  6356. Text('文件大小:')
  6357. .fontSize(14)
  6358. .fontColor($r('app.color.text_color'))
  6359. .margin({ left: 22 })
  6360. Text(currentItem.size)
  6361. .fontSize(14)
  6362. .margin({ left: 10 })
  6363. .fontColor($r('app.color.text_color'))
  6364. .layoutWeight(1)
  6365. }
  6366. .width('100%')
  6367. .margin({ top: 10, bottom: 10 })
  6368. .justifyContent(FlexAlign.Start)
  6369. Row() {
  6370. Text('文件名:')
  6371. .fontSize(14)
  6372. .fontColor($r('app.color.text_color'))
  6373. .margin({ left: 22 })
  6374. Text(currentItem.fileName)
  6375. .fontSize(14)
  6376. .margin({ left: 10 })
  6377. .fontColor($r('app.color.text_color'))
  6378. .layoutWeight(1)
  6379. }
  6380. .width('100%')
  6381. .margin({ top: 10, bottom: 10 })
  6382. .justifyContent(FlexAlign.Start)
  6383. Row() {
  6384. Text('修改时间:')
  6385. .fontSize(14)
  6386. .fontColor($r('app.color.text_color'))
  6387. .margin({ left: 22 })
  6388. Text(currentItem.cTime)
  6389. .fontSize(14)
  6390. .margin({ left: 10 })
  6391. .fontColor($r('app.color.text_color'))
  6392. .layoutWeight(1)
  6393. }
  6394. .width('100%')
  6395. .margin({ top: 10, bottom: 10 })
  6396. .justifyContent(FlexAlign.Start)
  6397. Row() {
  6398. Text('存放目录:')
  6399. .fontSize(14)
  6400. .fontColor($r('app.color.text_color'))
  6401. .margin({ left: 22 })
  6402. Text(currentItem.filePath)
  6403. .fontSize(12)
  6404. .margin({ left: 10 })
  6405. .fontColor($r('app.color.text_color'))
  6406. .layoutWeight(1)
  6407. }
  6408. .margin({ top: 10, bottom: 10 })
  6409. .width('100%')
  6410. .justifyContent(FlexAlign.Start)
  6411. Row() {
  6412. Text('内嵌歌词:')
  6413. .fontSize(14)
  6414. .fontColor($r('app.color.text_color'))
  6415. .margin({ left: 22 })
  6416. Text(currentItem.lyricContent)
  6417. .fontSize(12)
  6418. .copyOption(CopyOptions.InApp)
  6419. .margin({ left: 10 })
  6420. .fontColor($r('app.color.text_color'))
  6421. .layoutWeight(1)
  6422. }
  6423. .margin({ top: 10, bottom: 10 })
  6424. .width('100%')
  6425. .justifyContent(FlexAlign.Start)
  6426. }
  6427. }
  6428. .margin({ bottom: 20 })
  6429. }
  6430. //定时关闭布局
  6431. @Builder
  6432. TimeCloseSheet() {
  6433. Scroll() {
  6434. Column() {
  6435. this.TimeClose()
  6436. }
  6437. }
  6438. .width('100%')
  6439. .height('100%')
  6440. }
  6441. //倒计时关闭音乐,退出App功能实现。
  6442. @State selectedMinutes: number = 0 // 0表示未开启
  6443. @State remainingSeconds: number = 0
  6444. // 预设时间选项
  6445. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  6446. private formatTime(seconds: number): string {
  6447. const mins = Math.floor(seconds / 60)
  6448. const secs = seconds % 60
  6449. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  6450. }
  6451. // 开始倒计时
  6452. private handleTimeSelect(minutes: number) {
  6453. if (minutes === this.selectedMinutes) {
  6454. this.stopCountdown();
  6455. this.selectedMinutes = 0;
  6456. return;
  6457. }
  6458. this.selectedMinutes = minutes;
  6459. this.remainingSeconds = minutes * 60;
  6460. this.startCountdown(); // 新增调用
  6461. }
  6462. @Builder
  6463. TimeClose() {
  6464. Column() {
  6465. // 倒计时显示区域
  6466. Text(this.selectedMinutes > 0 ?
  6467. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  6468. "定时关闭未开启")
  6469. .fontSize(17)
  6470. .fontColor($r('app.color.text_color'))
  6471. .margin({ top: 2, bottom: 8 });
  6472. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6473. ForEach(this.presetTimes, (minutes: number, index: number) => {
  6474. // 单行时间选项容器
  6475. Row() {
  6476. // 文字描述区域
  6477. Text(this.getDisplayText(minutes))
  6478. .fontSize(15)
  6479. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  6480. $r('app.color.text_color'))// 选中态颜色变化
  6481. .textAlign(TextAlign.Start)
  6482. .layoutWeight(1); // 占据剩余空间
  6483. // 复选框样式的选择器
  6484. Row() {
  6485. if (minutes === this.selectedMinutes) {
  6486. // 选中状态 - 带勾号的圆形复选框
  6487. Row() {
  6488. // 使用系统内置的勾号图标
  6489. Image($r('sys.media.ohos_ic_public_ok'))
  6490. .width(14)
  6491. .height(14)
  6492. .fillColor(Color.White)
  6493. }
  6494. .width(24)
  6495. .height(24)
  6496. .borderRadius(12)
  6497. .backgroundColor(this.themeColor)
  6498. .justifyContent(FlexAlign.Center)
  6499. .alignItems(VerticalAlign.Center)
  6500. } else {
  6501. // 未选中状态的圆形边框
  6502. Row()
  6503. .width(24)
  6504. .height(24)
  6505. .borderRadius(12)
  6506. .border({
  6507. width: 2,
  6508. color: $r('app.color.text_color'),
  6509. style: BorderStyle.Solid
  6510. })
  6511. .backgroundColor(Color.Transparent)
  6512. }
  6513. }
  6514. .width(24)
  6515. .height(24)
  6516. .margin({ left: 20 })
  6517. .justifyContent(FlexAlign.Center)
  6518. .alignItems(VerticalAlign.Center)
  6519. }
  6520. .width('100%')
  6521. .padding({
  6522. top: 18,
  6523. bottom: 18,
  6524. left: 18,
  6525. right: 18
  6526. })
  6527. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  6528. $r('app.color.bottom_control_background')) // 选中背景高亮
  6529. .borderRadius(12)
  6530. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6531. .margin({ bottom: 18 })
  6532. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  6533. });
  6534. }
  6535. .width('100%')
  6536. .padding(16)
  6537. }
  6538. }
  6539. // 获取显示文本
  6540. private getDisplayText(minutes: number): string {
  6541. if (minutes === -1) {
  6542. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  6543. }
  6544. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  6545. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  6546. }
  6547. // 处理选择事件
  6548. private handleSelect(minutes: number): void {
  6549. if (minutes === -1) { // 自定义
  6550. // 弹出自定义时间对话框
  6551. DialogHelper.showTextInputDialog({
  6552. title: '自定义时间',
  6553. maskColor: Color.Transparent,
  6554. inputType: InputType.Number,
  6555. text: '',
  6556. onChange: (text) => {
  6557. console.error("onChange: " + text);
  6558. },
  6559. onAction: (action, dialogId, content) => {
  6560. if (action == DialogAction.TWO) {
  6561. const customMinutes = Number(content);
  6562. if (customMinutes > 0) {
  6563. this.handleTimeSelect(customMinutes); // 设置自定义时间
  6564. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  6565. }
  6566. }
  6567. }
  6568. });
  6569. } else {
  6570. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  6571. }
  6572. }
  6573. // 添加定时器引用
  6574. private timerId: number = -1;
  6575. // 启动/重置倒计时
  6576. private startCountdown() {
  6577. // 清除旧定时器
  6578. if (this.timerId !== -1) {
  6579. clearInterval(this.timerId);
  6580. }
  6581. // 创建新定时器
  6582. if (this.selectedMinutes > 0) {
  6583. this.timerId = setInterval(() => {
  6584. if (this.remainingSeconds === 15) {
  6585. this.showConfirmationDialog();
  6586. }
  6587. if (this.remainingSeconds > 0) {
  6588. this.remainingSeconds -= 1;
  6589. } else {
  6590. this.stopCountdown();
  6591. this.handleTimeout();
  6592. }
  6593. }, 1000);
  6594. }
  6595. }
  6596. // 15倒计时后再次提示显示确认是否关闭App对话框
  6597. private showConfirmationDialog() {
  6598. DialogHelper.showAlertDialog({
  6599. backgroundColor: $r('app.color.btn_green'),
  6600. title: '确认关闭',
  6601. maskColor: Color.Transparent,
  6602. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  6603. borderStyle: BorderStyle.Dashed,
  6604. primaryButton: '暂不关闭',
  6605. secondaryButton: '确定',
  6606. onAction: (action) => {
  6607. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  6608. this.stopCountdown();
  6609. this.selectedMinutes = 0
  6610. } else if (action == DialogAction.TWO) {
  6611. }
  6612. }
  6613. })
  6614. }
  6615. // 停止倒计时
  6616. private stopCountdown() {
  6617. if (this.timerId !== -1) {
  6618. clearInterval(this.timerId);
  6619. this.timerId = -1;
  6620. }
  6621. }
  6622. // 超时处理
  6623. private handleTimeout() {
  6624. // 执行播放器关闭逻辑
  6625. this.selectedMinutes = 0;
  6626. ToastUtil.showToast(" 定时关闭已完成");
  6627. this.stop(); // 假设存在的播放器实例
  6628. //退出APP
  6629. const mContext = getContext(this) as common.UIAbilityContext
  6630. mContext.terminateSelf();
  6631. AvSessionController.getInstance(true).unregisterSessionListener()
  6632. }
  6633. //倒计时关闭音乐,退出App功能实现结束。
  6634. //播放列表的拖动List 重新排序
  6635. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  6636. //左滑操作 移动文件 重命名 删除等操作
  6637. @Builder
  6638. sonButton(item: VideoItem, index: number, filePath: string) {
  6639. Row() {
  6640. //加入下一首播放
  6641. Button() {
  6642. Image($r('app.media.next_to_play'))
  6643. .fillColor(Color.White)
  6644. .width(20)
  6645. }
  6646. .width(40)
  6647. .height(40)
  6648. .type(ButtonType.Circle)
  6649. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6650. .backgroundColor(this.themeColor)
  6651. .margin(5)
  6652. .onClick(() => {
  6653. this.addToNextPlay(item);
  6654. })
  6655. Button() {
  6656. Image($r('app.media.close'))
  6657. .fillColor(Color.White)
  6658. .width(20)
  6659. }
  6660. .width(40)
  6661. .height(40)
  6662. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6663. .type(ButtonType.Circle)
  6664. .backgroundColor(this.themeColor)
  6665. .margin(5)
  6666. .onClick(() => {
  6667. this.songList.splice(Number(index), 1)
  6668. this.sonDataSource.pushArrayData(this.songList)
  6669. })
  6670. Button() {
  6671. Image($r('app.media.share2'))
  6672. .fillColor(Color.White)
  6673. .width(20)
  6674. }
  6675. .width(40)
  6676. .height(40)
  6677. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6678. .type(ButtonType.Circle)
  6679. .backgroundColor(this.themeColor)
  6680. .margin(5)
  6681. .onClick(() => {
  6682. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6683. })
  6684. }
  6685. }
  6686. itemMoveSon(index: number, newIndex: number): void {
  6687. if (newIndex < 0 || newIndex >= this.songList.length) {
  6688. return;
  6689. }
  6690. let tmp = this.songList.splice(index, 1);
  6691. this.songList.splice(newIndex, 0, tmp[0]);
  6692. this.sonDataSource.pushArrayData(this.songList)
  6693. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  6694. if(this.modeType==4&&this.playlistTable){
  6695. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  6696. }
  6697. }
  6698. @Builder
  6699. PlayList() {
  6700. List({ scroller: this.playListScroller }) {
  6701. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  6702. ListItem() {
  6703. this.MusicItemSon(item, index)
  6704. }
  6705. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  6706. .animation({
  6707. duration: 666,
  6708. curve: 'ease-in-out' // 可选动画曲线
  6709. })
  6710. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  6711. TransitionEffect.scale({ x: 0, y: 0 })))
  6712. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6713. //拖动List关键代码开始
  6714. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  6715. .zIndex(this.dragItem === index ? 1 : 0)
  6716. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  6717. .gesture(
  6718. GestureGroup(GestureMode.Sequence,
  6719. LongPressGesture({ repeat: true })
  6720. .onAction((event?: GestureEvent) => {
  6721. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6722. this.scaleItem = index
  6723. })
  6724. })
  6725. .onActionEnd(() => {
  6726. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6727. this.scaleItem = -1
  6728. })
  6729. }),
  6730. PanGesture({ fingers: 1, direction: null, distance: 0 })
  6731. .onActionStart(() => {
  6732. this.dragItem = index // 记录当前拖动项索引
  6733. this.dragRefOffset = 0 // 重置偏移基准
  6734. })
  6735. .onActionUpdate((event: GestureEvent) => {
  6736. this.offsetY = event.offsetY - this.dragRefOffset;
  6737. this.neighborItem = -1;
  6738. let indexA = this.songList.indexOf(item);
  6739. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6740. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6741. let value: number = 0;
  6742. if (this.offsetY < 0) {
  6743. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6744. this.neighborItem = indexA - 1;
  6745. this.neighborScale = 1 - value / 20;
  6746. } else if (this.offsetY > 0) {
  6747. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6748. this.neighborItem = indexA + 1;
  6749. this.neighborScale = 1 - value / 20;
  6750. }
  6751. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  6752. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6753. this.offsetY -= this.ITEM_INTV;
  6754. this.dragRefOffset += this.ITEM_INTV;
  6755. this.itemMoveSon(indexA, indexA + 1);
  6756. });
  6757. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6758. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6759. this.offsetY += this.ITEM_INTV;
  6760. this.dragRefOffset -= this.ITEM_INTV;
  6761. this.itemMoveSon(indexA, indexA - 1);
  6762. });
  6763. }
  6764. })
  6765. .onActionEnd((event: GestureEvent) => {
  6766. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6767. this.dragItem = -1
  6768. this.neighborItem = -1
  6769. })
  6770. animateTo({
  6771. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6772. }, () => {
  6773. this.scaleItem = -1
  6774. })
  6775. })
  6776. )
  6777. .onCancel(() => {
  6778. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6779. this.dragItem = -1
  6780. this.neighborItem = -1
  6781. })
  6782. animateTo({
  6783. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6784. }, () => {
  6785. this.scaleItem = -1
  6786. })
  6787. })
  6788. ) //拖动List关键代码结束
  6789. .onClick(() => {
  6790. this.doPlay(item, index, true)
  6791. })
  6792. }, (item: VideoItem) => item.filePath)
  6793. }
  6794. .width('100%')
  6795. .height('100%')
  6796. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  6797. // .animation({ duration: 500, curve: Curve.Ease }))
  6798. .cachedCount(10)
  6799. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6800. .gesture(PinchGesture({ fingers: 2 })
  6801. .onActionEnd((event: GestureEvent) => {
  6802. this.setSonListTwoFingers()
  6803. })
  6804. .onActionUpdate(e => {
  6805. this.scaleValue = this.pinchValue * e.scale
  6806. })
  6807. .onActionStart(e => {
  6808. }))
  6809. .padding({
  6810. bottom: 0
  6811. })
  6812. }
  6813. setSonListTwoFingers() {
  6814. this.pinchValue = this.scaleValue;
  6815. Logger.info('this.pinchValue = ' + this.pinchValue);
  6816. if (this.pinchValue >= 1) {
  6817. this.sonTwoFingerType++
  6818. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  6819. if (this.sonTwoFingerType > 3) {
  6820. this.sonTwoFingerType = 1
  6821. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6822. }
  6823. } else {
  6824. this.sonTwoFingerType--
  6825. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  6826. if (this.sonTwoFingerType < 1) {
  6827. this.sonTwoFingerType = 1
  6828. }
  6829. }
  6830. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  6831. this.pinchValue = 1;
  6832. this.scaleValue = 1;
  6833. }
  6834. @State sonTwoFingerType:number = 3
  6835. @Builder
  6836. private MusicItemSon(item: VideoItem, index?: number) {
  6837. Button({ type: ButtonType.Normal, stateEffect: true }) {
  6838. Row() {
  6839. Stack() {
  6840. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  6841. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6842. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6843. .alt($r('app.media.music_red'))
  6844. .fillColor(this.themeColor)
  6845. .borderRadius('100%')
  6846. .clip(true)
  6847. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  6848. .draggable(false)// 禁止长按手势拖动
  6849. .autoResize(true) // 重采样,可减少内存占用
  6850. .margin({ left: 20 })
  6851. }
  6852. .width('15%')
  6853. Column() {
  6854. Column() {
  6855. Text(this.isShowFileName?item.fileName :item.name)
  6856. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  6857. .fontColor(this.curIndex === index ? this.themeColor :
  6858. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  6859. .maxLines(1)
  6860. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  6861. Row() {
  6862. Column(){
  6863. Text(item.md5Str?.includes('Lossless')?
  6864. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6865. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  6866. .padding({ top: 3,right:6,left:6,bottom:3 })
  6867. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6868. $r('app.color.text_color'))
  6869. .fontWeight(500)
  6870. .borderRadius(12)
  6871. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  6872. .backgroundColor('#FFC107')
  6873. }
  6874. .padding({ top: 8 })
  6875. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  6876. item.artist + ' ' + item?.duration)
  6877. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6878. .padding({ top: 8 })
  6879. .maxLines(1)
  6880. .fontColor(this.curIndex === index ? this.themeColor :
  6881. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6882. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  6883. Blank()
  6884. Text(item.size)
  6885. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6886. .padding({ top: 8 })
  6887. .maxLines(1)
  6888. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  6889. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  6890. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6891. .margin({ left: 10 })
  6892. }
  6893. }
  6894. .height('100%')
  6895. .width('100%')
  6896. .justifyContent(FlexAlign.Center)
  6897. .alignItems(HorizontalAlign.Start)
  6898. }
  6899. .height('100%')
  6900. .width('65%')
  6901. Column() {
  6902. ImageAnimator()
  6903. .images(this.imagesF)// 动画数组
  6904. .duration(1000)// 持续
  6905. .state(this.animationState)// 动画状态
  6906. .fillMode(FillMode.Forwards)
  6907. .width(18)
  6908. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  6909. Visibility.None)
  6910. .height(18)
  6911. .iterations(-1) // 播放次数
  6912. }
  6913. .width('20%')
  6914. }
  6915. }
  6916. .backgroundColor(Color.Transparent)
  6917. .width('100%')
  6918. .reuseId('son_item')
  6919. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  6920. .shadow(this.scaleItem === index ? {
  6921. radius: 70,
  6922. color: '#15000000',
  6923. offsetX: 0,
  6924. offsetY: 0
  6925. } :
  6926. {
  6927. radius: 0,
  6928. color: '#15000000',
  6929. offsetX: 0,
  6930. offsetY: 0
  6931. })
  6932. .animation({ curve: Curve.Sharp, duration: 300 })
  6933. }
  6934. @Builder
  6935. MusicPlayBuilder() {
  6936. Column() {
  6937. this.IjkMusicPlayerView()
  6938. }
  6939. .height('100%')
  6940. .width('100%')
  6941. .onDisAppear(() => {
  6942. this.translateY = 0;
  6943. })
  6944. .translate({ y: this.translateY })
  6945. .gesture(
  6946. PanGesture(this.panOption)
  6947. .onActionUpdate((event?: GestureEvent) => {
  6948. if (event) {
  6949. // 只允许向下滑动,向上滑动时限制为0
  6950. this.translateY = Math.max(0, event.offsetY);
  6951. }
  6952. })
  6953. .onActionEnd((event?: GestureEvent) => {
  6954. // 使用更低的阈值和滑动速度判断
  6955. const minDistance = 100; // 最小滑动距离 100vp
  6956. const minVelocity = 500; // 最小滑动速度
  6957. // 获取滑动速度(如果可用)
  6958. const velocity = event?.velocityY || 0;
  6959. // 判断是否应该关闭:距离足够 或者 速度足够快
  6960. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  6961. if (shouldClose) {
  6962. // 添加关闭动画
  6963. this.getUIContext().animateTo({
  6964. duration: 300,
  6965. curve: Curve.Smooth
  6966. }, () => {
  6967. this.isShowPlay = false;
  6968. this.translateY = 0;
  6969. })
  6970. } else {
  6971. // 回弹动画
  6972. this.getUIContext().animateTo({
  6973. duration: 300,
  6974. curve: Curve.Smooth
  6975. }, () => {
  6976. this.translateY = 0;
  6977. })
  6978. }
  6979. })
  6980. )
  6981. }
  6982. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  6983. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  6984. HeightBreakpoint.HEIGHT_LG;
  6985. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  6986. @State topBarHeight: number = 50
  6987. @State barOpacity: number = 1
  6988. @State barBottomOpacity: number = 1
  6989. private hideDone: boolean = false;
  6990. @State currentYOffset: number = 0;
  6991. @State bottomBarHeight: number = 55;
  6992. private isHiding: boolean = false;
  6993. //是否是Pura X外屏,或者小屏幕
  6994. isPuraWP() {
  6995. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6996. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  6997. }
  6998. //是否是Pura X外屏,或者小屏幕,手机横屏
  6999. /**
  7000. * 是否是Pura X外屏,或者小屏幕,手机横屏
  7001. * @returns
  7002. */
  7003. isCoverOpacity() {
  7004. if (this.isPuraWP()) {
  7005. return true
  7006. }
  7007. if (this.isPhoneLan()) {
  7008. return true
  7009. }
  7010. if (deviceInfo.marketName.includes('Pura X')
  7011. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  7012. return true
  7013. }
  7014. return false
  7015. }
  7016. //是不是手机横屏
  7017. isPhoneLan() {
  7018. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  7019. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  7020. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  7021. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  7022. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  7023. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  7024. if (this.isHiCarKuanBianPing()) {
  7025. return true
  7026. }
  7027. if (this.isHiCar()) {
  7028. return false
  7029. }
  7030. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7031. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  7032. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  7033. return true
  7034. }
  7035. return false
  7036. }
  7037. //是不是1920x720的hicar的屏幕分辨率
  7038. isHiCarKuanBianPing(){
  7039. if(!this.isHiCar()){
  7040. return false
  7041. }
  7042. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7043. { ratio: 1920 / 720, name: "1920x720" },
  7044. ];
  7045. const currentRatio: number = this.windowWidth / this.windowHeight;
  7046. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7047. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  7048. for (const hiCarRatio of hiCarAspectRatios) {
  7049. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  7050. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7051. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7052. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7053. //宽扁平的尺寸设置列表展示
  7054. this.twoFingerType ==3
  7055. this.isGridMusic = false
  7056. return true;
  7057. }
  7058. }
  7059. return false;
  7060. }
  7061. //是不是hicar的屏幕分辨率
  7062. isHiCarSmall() {
  7063. if(!this.isHiCar()){
  7064. return false
  7065. }
  7066. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  7067. {
  7068. this.columns = 6
  7069. return false
  7070. }
  7071. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7072. { ratio: 800 / 480, name: "800x480" },
  7073. { ratio: 1280 / 720, name: "1280x720" },
  7074. { ratio: 1920 / 1080, name: "1920x1080" },
  7075. ];
  7076. const currentRatio: number = this.windowWidth / this.windowHeight;
  7077. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7078. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  7079. for (const hiCarRatio of hiCarAspectRatios) {
  7080. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  7081. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7082. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  7083. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7084. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7085. //宽扁平的尺寸设置列表展示
  7086. return true;
  7087. }
  7088. }
  7089. return false;
  7090. }
  7091. isHiCar() {
  7092. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  7093. }
  7094. //是不是正常的手机竖屏
  7095. isPhonePortrait() {
  7096. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  7097. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  7098. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  7099. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7100. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  7101. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  7102. return true
  7103. }
  7104. return false
  7105. }
  7106. @State showSpeedDialog: boolean = false
  7107. @State longPressSpeed: number = 3 //长按默认倍数
  7108. @Builder
  7109. SpeedDialog() {
  7110. Stack() {
  7111. Column() {
  7112. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7113. .fontColor(Color.White)
  7114. .visibility(Visibility.Hidden)
  7115. }
  7116. .backgroundColor(Color.Black)
  7117. .borderRadius(20)
  7118. .padding({
  7119. top: 10,
  7120. right: 20,
  7121. left: 15,
  7122. bottom: 20
  7123. })
  7124. .opacity(0.6)
  7125. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7126. .fontColor(Color.White)
  7127. }
  7128. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  7129. .zIndex(5)
  7130. .margin({ top: 80 })
  7131. }
  7132. @Builder
  7133. IjkMusicPlayerView() {
  7134. Column() {
  7135. Column() {
  7136. Column() {
  7137. //播放标题
  7138. Column() {
  7139. this.PlayTitle()
  7140. }
  7141. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  7142. .width('100%')
  7143. .margin({ top: 0 })
  7144. .height(PlayConstants.HEIGHT)
  7145. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  7146. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  7147. if (this.showSpeedDialog) {
  7148. this.SpeedDialog()
  7149. }
  7150. Stack() {
  7151. //手势拖动快进
  7152. Column()
  7153. .width(CommonConstants.FULL_PERCENT)
  7154. .height('100%')
  7155. .gesture(
  7156. GestureGroup(GestureMode.Parallel,
  7157. // 长按屏幕倍数播放
  7158. LongPressGesture({ repeat: true })
  7159. .onAction(() => {
  7160. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7161. this.showSpeedDialog = true;
  7162. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  7163. }
  7164. })
  7165. .onActionEnd(() => {
  7166. this.showSpeedDialog = false;
  7167. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7168. }),
  7169. //双击屏幕暂停或者播放
  7170. TapGesture({ count: 2 })
  7171. .onAction((event: GestureEvent) => {
  7172. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7173. ToastUtil.showToast('已暂停')
  7174. }
  7175. console.info('onecold playOrPause 6693')
  7176. this.playOrPause()
  7177. })
  7178. )
  7179. )
  7180. }
  7181. .height('65%')
  7182. Swiper() {
  7183. this.CoverInfo()
  7184. this.PlayerLyrics()
  7185. }
  7186. .onChange((index: number) => {
  7187. this.currentSwiperIndex = index
  7188. })
  7189. .indicator(false)
  7190. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  7191. // new DotIndicator()
  7192. // .top(this.isCoverOpacity()?0:10)
  7193. //
  7194. // .selectedColor($r('app.color.select_swiper'))
  7195. // .color($r('app.color.slider_track')):false
  7196. // )
  7197. .displayCount(new BreakpointType({
  7198. sm: 1,
  7199. md: 2,
  7200. lg: 2,
  7201. xl: 2,
  7202. xxl: 2
  7203. }).getValue(this.currentBreakpoint))
  7204. .clip(false)
  7205. .loop(false)
  7206. .autoPlay(false)
  7207. // .interval(8000)
  7208. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  7209. .height('100%')
  7210. .hitTestBehavior(HitTestMode.Transparent)
  7211. Image($r('app.media.icon_replay'))
  7212. .objectFit(ImageFit.Auto)
  7213. .width('120px')
  7214. .height('120px')
  7215. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  7216. .border({ width: 0 })
  7217. .visibility(Visibility.None)
  7218. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  7219. .onClick(() => {
  7220. console.info('onecold startPlayOrResumePlay 6744')
  7221. this.startPlayOrResumePlay();
  7222. })
  7223. }
  7224. .width(CommonConstants.FULL_PERCENT)
  7225. .height(CommonConstants.FULL_PERCENT)
  7226. .justifyContent(FlexAlign.End)
  7227. }
  7228. .justifyContent(FlexAlign.End)
  7229. .margin({ bottom: 8 })
  7230. }
  7231. .backgroundImage(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7232. // .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  7233. // (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  7234. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  7235. // .backgroundImagePosition(Alignment.Center)
  7236. .animation({
  7237. duration: 666,
  7238. curve: 'ease-in-out' // 可选动画曲线
  7239. })
  7240. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  7241. BlurStyle.BACKGROUND_ULTRA_THICK)
  7242. .hitTestBehavior(HitTestMode.Transparent)
  7243. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  7244. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  7245. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  7246. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  7247. .onClick(() => {
  7248. // this.startAutoHide()
  7249. if(this.isHiCar())
  7250. return
  7251. if(this.is_auto_hide_progress){
  7252. this.is_auto_hide_progress = false
  7253. }
  7254. this.startAutoHide()
  7255. })
  7256. }
  7257. @State progressValue: number = 0;
  7258. @State currentTime: string = "00:00";
  7259. @State totalTime: string = "00:00";
  7260. @State loadingVisible: Visibility = Visibility.None;
  7261. @State replayVisible: Visibility = Visibility.None;
  7262. @State slideEnable: boolean = false;
  7263. @State aspRatio: number = 0.5;
  7264. @State mContext: object | undefined = undefined;
  7265. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  7266. @State mFirst: boolean = true;
  7267. @State mDestroyPage: boolean = false;
  7268. @State playSpeed: number = 1;
  7269. @State oldSeconds: number = 0;
  7270. @State isSeekTo: boolean = false;
  7271. @State isCurrentTime: boolean = false;
  7272. @State videoWidth: string = '100%';
  7273. @State videoHeight: string = '100%';
  7274. @State initAspectRatio: number = 1;
  7275. @State videoAspectRatio: number = this.initAspectRatio;
  7276. private videoUrl: string = '';
  7277. private last: number = 0;
  7278. @State videoParentAspectRatio: number = this.initAspectRatio;
  7279. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  7280. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  7281. @State PROGRESS_MAX_VALUE: number = 100;
  7282. @State updateProgressTimer: number = 0;
  7283. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  7284. @State name: string = '';
  7285. // @State loop: boolean = false;
  7286. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  7287. @State multiple: string = '1.0X';
  7288. xcomponentController: XComponentController = new XComponentController()
  7289. private panOptionBright: PanGestureOptions =
  7290. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  7291. private panOptionVolume: PanGestureOptions =
  7292. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  7293. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  7294. //手势的音量控制和亮度控制
  7295. private positionX: number = PlayConstants.POSITION_X;
  7296. private positionY: number = PlayConstants.POSITION_Y;
  7297. private windowClass: window.Window = globalThis.windowClass
  7298. @State volume: number = 0.5;
  7299. @State volumeSmall: boolean = false
  7300. @State autoParseMusicName: boolean = true
  7301. @State isShowFileName: boolean = false
  7302. @State isLongNameRoLL: boolean = true//长歌名滚动
  7303. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  7304. @State bright: number = PlayConstants.BRIGHT;
  7305. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  7306. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  7307. @State screenWidth: number = 0
  7308. @State screenHeight: number = 0
  7309. @State statusBarHeight: number = 0
  7310. @State isYesFull: boolean = false
  7311. private seekValue: number = 0
  7312. @State isVideoLock: boolean = false; // Whether the video playback is locked
  7313. eventHub = getContext().eventHub;
  7314. //投播组件
  7315. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  7316. private castController: avSession.AVCastController | undefined = undefined;
  7317. @State isCastPlaying: boolean = false;
  7318. @State currentTime2: number = 0;
  7319. @State currentStringTime: string = '00:00';
  7320. @State duration: number = 0;
  7321. @State isReady: boolean = false;
  7322. @State durationTime: number = 0;
  7323. @State durationStringTime: string = '00:00';
  7324. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  7325. // @State isPlaying: boolean = false;
  7326. private castSeek: boolean = false;
  7327. private castItem: avSession.AVQueueItem | undefined = undefined;
  7328. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  7329. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  7330. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  7331. @State rotateAngle2: number = -9
  7332. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  7333. @State cover: string | undefined = '';
  7334. @State artist: string | undefined = ''
  7335. // 1.初始化controller
  7336. private lyricController: LyricController = new LyricController()
  7337. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  7338. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  7339. private parser = new LyricParser()
  7340. @State randomColor: string = 'rgb(0,0,0)'
  7341. @State randomShakenX: number = 0
  7342. @State randomShakenY: number = 0
  7343. @State lyricTextSize: number = 24
  7344. @State lyricContent: string = ''
  7345. @State isDebug: boolean = false
  7346. @State isHightLightCenter: boolean = true
  7347. /**
  7348. * 初始化歌词加载与展示逻辑
  7349. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  7350. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  7351. * @param isApi2 是否使用API2获取歌词(可选)
  7352. *
  7353. * 主要流程:
  7354. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  7355. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  7356. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  7357. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  7358. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  7359. * 6. 解析失败或读取失败时,清空歌词显示。
  7360. *
  7361. * 注意事项:
  7362. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  7363. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  7364. * - 歌词内容解析后通过lyricController驱动UI渲染。
  7365. */
  7366. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  7367. if (StrUtil.isEmpty(lyricPath)) {
  7368. return
  7369. }
  7370. this.initPipLyricSetting()
  7371. this.lyricControllerSingle
  7372. .setTextSize(15)
  7373. .setCacheSize(4)
  7374. .setTextColor("#FFFFFF")
  7375. .setHighlightColor("#FFFFFF")
  7376. .setHighlightScale(1.2)
  7377. .setEmptyHint("")
  7378. .setAlignMode('center')
  7379. .setAnimationDuration(500)
  7380. .setSingleLine(true)
  7381. this.lyricContent = ''
  7382. this.lyricController
  7383. .setTextSize(this.currentLyricSize)
  7384. .setCacheSize(4)
  7385. .setTextColor("#DDDDDD")
  7386. .setHighlightColor("#FFFFFF")
  7387. .setEmptyHint("")
  7388. .setAnimationDuration(1000)
  7389. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  7390. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  7391. this.setBlurDegree(this.blurDegree, false)
  7392. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  7393. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  7394. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  7395. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  7396. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  7397. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  7398. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  7399. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7400. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  7401. this.lyricController.setTextWeight(this.lyricTextWeight)
  7402. this.showSingleLyric = false
  7403. this.timeOffset = 0
  7404. this.lyricController.setLyric(null)
  7405. this.lyricControllerSingle.setLyric(null)
  7406. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  7407. console.log("onecold lyricPath =" + lyricPath)
  7408. let neiqianLrc = ''
  7409. let lyContent = this.currentSong?.lyricContent
  7410. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  7411. neiqianLrc = lyContent
  7412. }
  7413. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  7414. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  7415. //赋值给this.lyricContent,播控中心才可以显示歌词
  7416. this.lyricContent = neiqianLrc
  7417. // 将文件内容按行分割成字符串数组
  7418. let lines = neiqianLrc.split('\n').map(line => line.trim());
  7419. // 3.解析歌词
  7420. let lyric = this.parser.parse(lines);
  7421. // 4.设置歌词
  7422. this.lyricController.setLyric(lyric);
  7423. this.lyricControllerXF.setLyric(lyric)
  7424. this.lyricControllerSingle.setLyric(lyric)
  7425. return
  7426. }
  7427. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  7428. && !Utility.isVideoByExtension(this.videoUrl))) {
  7429. if (this.currentSong !== undefined) {
  7430. // ToastUtil.showShort('正在为你搜索在线歌词!')
  7431. //判断是不是赞助会员,是会员的话才开启歌词功能
  7432. // if (!this.isDebug) {
  7433. // if (!Utility.isNoble()) {
  7434. // LogUtil.debug("onecold 不是赞助会员")
  7435. // return
  7436. // }
  7437. // if(!Utility.isPassInstallTime(33)){
  7438. // LogUtil.debug("onecold not pass time")
  7439. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  7440. // return
  7441. // }
  7442. // }
  7443. let artist = this.currentSong?.artist
  7444. if (artist === undefined) {
  7445. artist = ''
  7446. }
  7447. if (isApi2 === undefined) {
  7448. isApi2 = false
  7449. }
  7450. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  7451. // LogUtil.debug("onecold res =" + res)
  7452. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7453. if (StrUtil.isNotEmpty(res)) {
  7454. this.lyricContent = res
  7455. let lines = res.split('\n').map(line => line.trim());
  7456. // 3.解析歌词
  7457. let lyric = this.parser.parse(lines);
  7458. // 4.设置歌词
  7459. this.lyricController.setLyric(lyric);
  7460. this.lyricControllerXF.setLyric(lyric)
  7461. this.lyricControllerSingle.setLyric(lyric)
  7462. this.showSingleLyric = true
  7463. // 4.保存歌词文件lyric到本地
  7464. //2025年8月28日歌词不再加密下载
  7465. this.saveDataToFile(res, lyricPath, false)
  7466. } else {
  7467. this.lyricController.setLyric(null)
  7468. this.lyricControllerXF.setLyric(null)
  7469. this.lyricControllerSingle.setLyric(null)
  7470. if (isOnLineAndToast) {
  7471. ToastUtil.showShort('未获取到歌词!')
  7472. }
  7473. }
  7474. } else {
  7475. this.lyricController.setLyric(null)
  7476. this.lyricControllerXF.setLyric(null)
  7477. this.lyricControllerSingle.setLyric(null)
  7478. if (isOnLineAndToast) {
  7479. ToastUtil.showShort('未获取到歌词!')
  7480. }
  7481. }
  7482. })
  7483. } else {
  7484. this.lyricController.setLyric(null)
  7485. this.lyricControllerXF.setLyric(null)
  7486. this.lyricControllerSingle.setLyric(null)
  7487. if (isOnLineAndToast) {
  7488. ToastUtil.showShort('未获取到歌词!')
  7489. }
  7490. }
  7491. return
  7492. }
  7493. try {
  7494. let isJiaMi = false;
  7495. let realLyricPath = lyricPath
  7496. if (FileUtil.accessSync(jiaMilyricPath)) {
  7497. isJiaMi = true
  7498. realLyricPath = jiaMilyricPath
  7499. console.info("onecold 找到加密本地歌词 ");
  7500. } else {
  7501. isJiaMi = false
  7502. realLyricPath = lyricPath
  7503. console.info("onecold 找到本地歌词 ");
  7504. }
  7505. // 3.读取文件内容并指定编码为 UTF-8
  7506. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7507. const stat = await fileIo.stat(file.fd);
  7508. const arrayBuffer = new ArrayBuffer(stat.size);
  7509. fs.read(file.fd, arrayBuffer)
  7510. .then((readLen: number) => {
  7511. console.info("read file data succeed");
  7512. // let buf = buffer.from(arrayBuffer, 0, readLen);
  7513. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7514. // 检查 buf 是否为空
  7515. if (buf.length === 0) {
  7516. throw new Error("Buffer is empty after reading the file");
  7517. }
  7518. try {
  7519. // 检测文件编码
  7520. // let detectedEncoding = chardet.detect(buf);
  7521. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  7522. let detectedEncoding = this.detect(arrayBuffer)
  7523. console.info("onecoldT Detected encoding: " + detectedEncoding);
  7524. // 使用检测到的编码解码,解决中文乱码问题
  7525. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7526. console.info("onecoldT Detected textDecoder: " + textDecoder);
  7527. let fileContent = textDecoder.decode(buf);
  7528. console.info(`onecoldT The content of file1: ${fileContent}`);
  7529. //解密
  7530. if (isJiaMi) {
  7531. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  7532. }
  7533. console.info(`onecold The content of file2: ${fileContent}`);
  7534. this.lyricContent = fileContent
  7535. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  7536. this.lyricConStr = fileContent
  7537. }
  7538. // 将文件内容按行分割成字符串数组
  7539. let lines = fileContent.split('\n').map(line => line.trim());
  7540. console.info(`onecold The content of file: ${fileContent}`);
  7541. // 3.解析歌词
  7542. let lyric = this.parser.parse(lines);
  7543. // 4.设置歌词
  7544. this.lyricController.setLyric(lyric);
  7545. this.lyricControllerXF.setLyric(lyric)
  7546. this.lyricControllerSingle.setLyric(lyric)
  7547. this.showSingleLyric = true
  7548. console.info(`The content of file: ${fileContent}`);
  7549. } catch (chardetError) {
  7550. console.error("chardet.detect failed with error: " + chardetError.message);
  7551. this.lyricController.setLyric(null);
  7552. this.lyricControllerXF.setLyric(null)
  7553. this.lyricControllerSingle.setLyric(null)
  7554. }
  7555. })
  7556. .catch((err: BusinessError) => {
  7557. this.lyricController.setLyric(null)
  7558. this.lyricControllerXF.setLyric(null)
  7559. this.lyricControllerSingle.setLyric(null)
  7560. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  7561. })
  7562. .catch((err: Error) => {
  7563. this.lyricController.setLyric(null)
  7564. this.lyricControllerXF.setLyric(null)
  7565. this.lyricControllerSingle.setLyric(null)
  7566. console.error("read file 2 data failed with error message: " + err.message);
  7567. })
  7568. .finally(() => {
  7569. fs.closeSync(file);
  7570. });
  7571. } catch (error) {
  7572. this.lyricController.setLyric(null)
  7573. this.lyricControllerSingle.setLyric(null)
  7574. this.lyricControllerXF.setLyric(null)
  7575. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  7576. }
  7577. }
  7578. detect(data: ArrayBuffer): string {
  7579. //创建检测对象
  7580. let detector: UniversalDetector = new UniversalDetector();
  7581. // 传入检测数据并实时判断编码格式
  7582. detector.handleData(data, 0, data.byteLength);
  7583. // 标记检测数据 读取结束
  7584. detector.dataEnd();
  7585. // 获取检测结果
  7586. let detected: string = detector.getDetectedCharset();
  7587. // 释放资源
  7588. detector.reset();
  7589. return detected;
  7590. }
  7591. //初始化悬浮歌词的自定义设置
  7592. initPipLyricSetting() {
  7593. this.lyricControllerXF
  7594. .setTextSize(this.currentLyricSize)
  7595. .setCacheSize(4)
  7596. .setTextColor("#DDDDDD")
  7597. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  7598. .setEmptyHint("")
  7599. .setAnimationDuration(1000)
  7600. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  7601. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  7602. this.setBlurDegree(this.blurDegreePip, true)
  7603. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  7604. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  7605. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  7606. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  7607. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  7608. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  7609. this.lyricControllerXF.setHightLightCenter(true)
  7610. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  7611. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7612. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7613. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  7614. if (this.pipBgIndex === 0) {
  7615. if (this.cover) {
  7616. this.pipBg = this.cover
  7617. } else {
  7618. this.pipBg = this.imageColor
  7619. }
  7620. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7621. }
  7622. }
  7623. //根据item返回歌词内容
  7624. async getLyricContent(item: VideoItem): Promise<string> {
  7625. let neiqianLrc = ''
  7626. let lyContent = item?.lyricContent
  7627. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  7628. neiqianLrc = lyContent
  7629. return neiqianLrc
  7630. }
  7631. try {
  7632. //取数据库里面的歌词lyContent
  7633. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  7634. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  7635. console.log("onecold Lyrics:", lyricContent);
  7636. neiqianLrc = lyricContent
  7637. return neiqianLrc
  7638. }
  7639. } catch (error) {
  7640. console.error("Error fetching lyrics:", error);
  7641. }
  7642. try {
  7643. let filePath = item.filePath;
  7644. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  7645. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  7646. let isJiaMi = false;
  7647. let realLyricPath = lyricPath;
  7648. if (FileUtil.accessSync(jiaMilyricPath)) {
  7649. isJiaMi = true;
  7650. realLyricPath = jiaMilyricPath;
  7651. console.info("onecold 找到加密本地歌词");
  7652. } else {
  7653. console.info("onecold 找到本地歌词");
  7654. }
  7655. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7656. const stat = await fileIo.stat(file.fd);
  7657. const arrayBuffer = new ArrayBuffer(stat.size);
  7658. const readLen = await fs.read(file.fd, arrayBuffer);
  7659. console.info("read file data succeed");
  7660. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7661. if (buf.length === 0) {
  7662. throw new Error("Buffer is empty after reading the file");
  7663. }
  7664. // let detectedEncoding = chardet.detect(buf);
  7665. let detectedEncoding = this.detect(arrayBuffer)
  7666. console.info("Detected encoding: " + detectedEncoding);
  7667. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7668. let fileContent = textDecoder.decode(buf);
  7669. console.info(`onecold The content of file1: ${fileContent}`);
  7670. if (isJiaMi) {
  7671. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  7672. }
  7673. console.info(`onecold The content of file2: ${fileContent}`);
  7674. fs.closeSync(file);
  7675. return fileContent;
  7676. } catch (error) {
  7677. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  7678. return '';
  7679. }
  7680. }
  7681. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  7682. if (StrUtil.isEmpty(filePath)) {
  7683. return
  7684. }
  7685. try {
  7686. //将content进行加密
  7687. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  7688. let lyricContent = ''
  7689. if (isJiaMi) {
  7690. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  7691. } else {
  7692. lyricContent = content
  7693. }
  7694. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  7695. // 清空文件内容
  7696. await fileIo.truncate(file.fd, 0);
  7697. await fileIo.write(file.fd, lyricContent);
  7698. await fileIo.close(file);
  7699. console.log('onecold lyric file Data saved successfully.');
  7700. } catch (error) {
  7701. console.error('onecold lyric file Failed to save data:', error);
  7702. }
  7703. }
  7704. /**
  7705. * Get largest proportion color of an image.
  7706. */
  7707. getImageColor() {
  7708. if (!this.context) {
  7709. return;
  7710. }
  7711. let bg = Utility.getMusisBg()
  7712. this.imageLabel = bg
  7713. ColorConversion.setSysBarLightBackground(true);
  7714. this.context.resourceManager.getMediaContent(bg)
  7715. .then((value: Uint8Array) => {
  7716. let buffer = value.buffer as ArrayBuffer;
  7717. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  7718. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  7719. if (error) {
  7720. Logger.error('Failed to create color picker.');
  7721. } else {
  7722. let color = colorPicker.getLargestProportionColor();
  7723. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  7724. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  7725. }
  7726. })
  7727. let headFilter = effectKit.createEffect(pixelMap);
  7728. if (headFilter !== null) {
  7729. headFilter.blur(15);
  7730. headFilter.getEffectPixelMap().then((value) => {
  7731. this.imageLabelBg = value;
  7732. })
  7733. }
  7734. })
  7735. .catch((error: BusinessError) => {
  7736. Logger.error(`${error.code} + ${error.message}`)
  7737. })
  7738. })
  7739. .catch((error: BusinessError) => {
  7740. Logger.error(`${error.code} + ${error.message}`)
  7741. })
  7742. }
  7743. setImageColor(cover: string) {
  7744. if (!this.context) {
  7745. return;
  7746. }
  7747. if (cover === undefined) {
  7748. return;
  7749. }
  7750. imagePathToPixelMap(cover).then((value) => {
  7751. let headFilter = effectKit.createEffect(value);
  7752. if (headFilter !== null) {
  7753. headFilter.blur(15);
  7754. headFilter.getEffectPixelMap().then((value) => {
  7755. this.imageLabelBg = value;
  7756. })
  7757. }
  7758. }).catch((error: BusinessError) => {
  7759. Logger.error(`${error.code} + ${error.message}`)
  7760. })
  7761. }
  7762. setImageColor2(cover: string) {
  7763. if (!this.context) {
  7764. return;
  7765. }
  7766. if (cover === undefined) {
  7767. return;
  7768. }
  7769. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  7770. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  7771. this.imageColor = data.imageColor;
  7772. if (data.blurPixelMap) {
  7773. this.imageLabelBg = data.blurPixelMap;
  7774. }
  7775. })
  7776. }
  7777. // 定义开始旋转的方法
  7778. // 定时器用于一百毫秒执行一次旋转角度
  7779. @State timer: number = 0
  7780. @State rotateAngle: number = 0
  7781. //封面旋转动画
  7782. animationRoFun() {
  7783. if (this.isPlaying && !this.isCoverRectangle) {
  7784. this.timer = setInterval(() => {
  7785. this.rotateAngle += 1
  7786. }, 100)
  7787. this.startRotation()
  7788. } else {
  7789. clearInterval(this.timer)
  7790. this.stopRotation()
  7791. }
  7792. }
  7793. // 定义开始旋转的方法
  7794. startRotation() {
  7795. if (this.isPlaying) {
  7796. animateTo({
  7797. duration: 777,
  7798. iterations: 1,
  7799. curve: Curve.Linear
  7800. }, () => {
  7801. this.rotateAngle2 = -9
  7802. })
  7803. }
  7804. }
  7805. // 回调,暂停和播放按钮回调,下一首和上一首
  7806. playChange() {
  7807. // if(this.isCoverRectangle){
  7808. // return
  7809. // }
  7810. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7811. this.setIsPlaying(true)
  7812. this.animationState = AnimationStatus.Running
  7813. } else {
  7814. this.setIsPlaying(false)
  7815. this.animationState = AnimationStatus.Paused
  7816. }
  7817. }
  7818. // 定义停止旋转的方法
  7819. stopRotation() {
  7820. if (this.isCoverRectangle) {
  7821. this.rotateAngle = 0
  7822. } else {
  7823. //唱针以左上角为点选择逆时针40度
  7824. animateTo({
  7825. duration: 1000,
  7826. curve: Curve.Linear,
  7827. iterations: 1,
  7828. }, () => {
  7829. this.rotateAngle2 = -45;
  7830. });
  7831. }
  7832. }
  7833. @Builder
  7834. private LyricsTopItem() {
  7835. Row() {
  7836. Stack() {
  7837. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7838. .height(58)
  7839. .width(58)
  7840. .alt(this.imageLabel)
  7841. .borderRadius(8)
  7842. .clickEffect({ level: ClickEffectLevel.HEAVY })
  7843. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  7844. .shadow({
  7845. radius: 22,
  7846. type: ShadowType.BLUR,
  7847. color: 'on_primary'
  7848. })
  7849. }
  7850. .width('18%')
  7851. Column() {
  7852. Column() {
  7853. Text(this.name)
  7854. .fontSize(16)
  7855. .maxLines(1)
  7856. .fontWeight(FontWeight.Bolder)
  7857. .fontColor(this.currentLyricColor)
  7858. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  7859. Row() {
  7860. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  7861. .fontSize(13)
  7862. .fontWeight(FontWeight.Bold)
  7863. .padding({ top: 8 })
  7864. .fontColor(this.currentLyricColor)
  7865. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  7866. Blank()
  7867. }
  7868. }
  7869. .height('100%')
  7870. .width('100%')
  7871. .justifyContent(FlexAlign.Center)
  7872. .alignItems(HorizontalAlign.Start)
  7873. }
  7874. .height('100%')
  7875. .width('65%')
  7876. Column() {
  7877. Image($r('app.media.lyric'))
  7878. .width(28)
  7879. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7880. .margin({ right: 30 })
  7881. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7882. .onClick(() => {
  7883. this.isLyricSetting = !this.isLyricSetting;
  7884. })
  7885. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  7886. height: '95%',
  7887. dragBar: true,
  7888. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7889. showClose: true,
  7890. blurStyle: BlurStyle.Thin,
  7891. backgroundColor: Color.Transparent,
  7892. // title: { title: $r('app.string.lyric_setting') }
  7893. })
  7894. }
  7895. .width('18%')
  7896. }
  7897. .width('82%')
  7898. .height(58)
  7899. .justifyContent(FlexAlign.SpaceBetween)
  7900. }
  7901. //歌词显示
  7902. @Builder
  7903. PlayerLyrics() {
  7904. Column() {
  7905. Column() {
  7906. this.LyricsTopItem()
  7907. }
  7908. .height(this.isPuraWP() ? 15 : 58)
  7909. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  7910. Visibility.None : Visibility.Visible)
  7911. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  7912. .width("100%")
  7913. Column() {
  7914. LyricView2({
  7915. controller: this.lyricController,
  7916. enableSeek: true,
  7917. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7918. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7919. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7920. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  7921. if (!this.isPlaying) {
  7922. console.info('onecold startPlayOrResumePlay 7527')
  7923. this.startPlayOrResumePlay()
  7924. }
  7925. else {
  7926. this.isSeekTo = true;
  7927. this.mDestroyPage = false;
  7928. this.showLoadIng();
  7929. this.seekTo(position + "");
  7930. this.isSeekTo = false;
  7931. }
  7932. return true
  7933. }
  7934. })
  7935. .width("100%")
  7936. .layoutWeight(1)
  7937. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  7938. if (this.isPhoneLan()) {
  7939. Column() {
  7940. this.playProgressView()
  7941. // this.playCenterView()
  7942. }
  7943. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  7944. }
  7945. }
  7946. .position({
  7947. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  7948. (this.isPuraWP() ? 58 : 99)
  7949. })
  7950. .justifyContent(FlexAlign.Center)
  7951. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  7952. }
  7953. }
  7954. @Builder
  7955. SingleLyricView() {
  7956. Column() {
  7957. Column() {
  7958. LyricView2({
  7959. controller: this.lyricControllerSingle,
  7960. enableSeek: false,
  7961. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7962. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7963. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7964. })
  7965. }
  7966. .height(66)
  7967. .margin({ bottom: 20 })
  7968. }
  7969. }
  7970. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  7971. @Builder
  7972. BottomControl() {
  7973. Column() {
  7974. this.TopPlayProgressView()
  7975. //播放 暂停,下一首,上一首
  7976. this.playCenterView()
  7977. //播放进度条
  7978. this.BottomView()
  7979. }
  7980. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  7981. }
  7982. //播放控制上一首 下一首 暂停和播放
  7983. @Builder
  7984. playCenterView(){
  7985. Row() {
  7986. Row({ space: 20 }) {
  7987. Button({type:ButtonType.Circle,stateEffect:true}){
  7988. //更多功能
  7989. Image($r('app.media.menu'))
  7990. .width(24)
  7991. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7992. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  7993. height: this.isCoverOpacity() ? '95%' : '93%',
  7994. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  7995. dragBar: true,
  7996. showClose: true,
  7997. blurStyle: BlurStyle.Thin,
  7998. backgroundColor: Color.Transparent,
  7999. })
  8000. }
  8001. .margin({ left: 5 })
  8002. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8003. .backgroundColor(Color.Transparent)
  8004. .onClick(() => {
  8005. this.isShowMoreView = !this.isShowMoreView;
  8006. })
  8007. Button({type:ButtonType.Circle,stateEffect:true}){
  8008. Image($r('app.media.ic_previous'))
  8009. .width(33)
  8010. .clickEffect({level:ClickEffectLevel.HEAVY})
  8011. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8012. }
  8013. .onClick(async () => {
  8014. this.playPrevious()
  8015. })
  8016. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8017. .backgroundColor(Color.Transparent)
  8018. .margin({ left: 5 })
  8019. }
  8020. Button({type:ButtonType.Circle,stateEffect:true}){
  8021. Column() {
  8022. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  8023. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  8024. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  8025. .width(this.isPhoneLan()?45:55)
  8026. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8027. .fillColor(Color.White)
  8028. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8029. .onClick(async () => {
  8030. console.info('onecold playOrPause 7651')
  8031. this.playOrPause()
  8032. })
  8033. }
  8034. }
  8035. .backgroundColor(Color.Transparent)
  8036. .layoutWeight(1)
  8037. // .margin({ left: 38, right: 38 })
  8038. Row({ space: 20 }) {
  8039. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8040. Image($r('app.media.ic_next'))
  8041. .width(33)
  8042. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8043. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8044. .onClick(() => {
  8045. this.playNext();
  8046. })
  8047. }
  8048. .backgroundColor(Color.Transparent)
  8049. .margin({ right: 5 })
  8050. .width(33)
  8051. if(this.isPhoneLan()){
  8052. this.fullButton()
  8053. }else{
  8054. Button({type:ButtonType.Circle,stateEffect:true}){
  8055. //添加或取消收藏
  8056. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  8057. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  8058. .fontSize(23)
  8059. .fontColor([Color.White])
  8060. .alignSelf(ItemAlign.Center)
  8061. // .width(24)
  8062. .clickEffect({level:ClickEffectLevel.MIDDLE})
  8063. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8064. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8065. .onClick(async () => {
  8066. if(this.currentSong){
  8067. this.doFav(this.currentSong)
  8068. }
  8069. })
  8070. }
  8071. .backgroundColor(Color.Transparent)
  8072. .width(24)
  8073. }
  8074. }
  8075. // .margin({ left: 5 })
  8076. }
  8077. .width('95%')
  8078. .margin({ bottom:this.isCoverOpacity()?0:20 })
  8079. .justifyContent(FlexAlign.SpaceEvenly)
  8080. }
  8081. @Builder
  8082. TopPlayProgressView(){
  8083. Row() {
  8084. Column(){
  8085. Row(){
  8086. Stack(){
  8087. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  8088. .fontColor([Color.White])
  8089. .fontSize(21)
  8090. .effectStrategy(1)
  8091. Text(this.fastForwardSeconds)
  8092. .fontColor(Color.White)
  8093. .fontSize(10)
  8094. .fontWeight(FontWeight.Bold)
  8095. }
  8096. .margin({left:12,bottom:6})
  8097. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8098. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8099. .onClick(()=>{
  8100. this.backForward()
  8101. })
  8102. Slider({
  8103. value: this.progressValue,
  8104. min: 0,
  8105. max: this.PROGRESS_MAX_VALUE,
  8106. step: 1,
  8107. style: SliderStyle.InSet
  8108. })
  8109. .height(20)
  8110. .blockColor('rgba(255,255,255,1)')
  8111. .trackColor('rgba(255,255,255,0.3)')
  8112. .selectedColor(Color.White)
  8113. .trackThickness(4)
  8114. .layoutWeight(1)
  8115. .showSteps(false)
  8116. .showTips(true)
  8117. .alignSelf(ItemAlign.Center)
  8118. .enabled(this.slideEnable)
  8119. .onChange((value: number, mode: SliderChangeMode) => {
  8120. // if (mode == 2) {
  8121. this.isSeekTo = true;
  8122. this.mDestroyPage = false;
  8123. this.showLoadIng();
  8124. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8125. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8126. this.seekTo(seekValue + "");
  8127. // this.setProgress()
  8128. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8129. this.isSeekTo = false;
  8130. // }
  8131. })
  8132. Stack(){
  8133. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  8134. .fontColor([Color.White])
  8135. .fontSize(21)
  8136. .effectStrategy(1)
  8137. Text(this.fastForwardSeconds)
  8138. .fontColor(Color.White)
  8139. .fontSize(10)
  8140. .fontWeight(FontWeight.Bold)
  8141. }
  8142. .margin({right:10,bottom:6})
  8143. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8144. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8145. .onClick(()=>{
  8146. this.fastForward()
  8147. })
  8148. }
  8149. .padding({ right: 7,left:22 })
  8150. Row(){
  8151. Text(this.currentTime)
  8152. .fontSize(10)
  8153. .fontColor(Color.White)
  8154. Blank()
  8155. .layoutWeight(1)
  8156. Text(this.totalTime)
  8157. .fontSize(10)
  8158. .fontColor(Color.White)
  8159. }
  8160. .justifyContent(FlexAlign.Start)
  8161. .padding({ right: 18,left:36 })
  8162. }
  8163. }
  8164. //x5的竖屏模式需要99%
  8165. .width(this.isLandscape?'80%':'93%')
  8166. .justifyContent(FlexAlign.Center)
  8167. .margin({bottom:6})
  8168. .animation({
  8169. duration: 666,
  8170. curve: 'ease-in-out' // 可选动画曲线
  8171. })
  8172. }
  8173. //播放进度条
  8174. @Builder
  8175. BottomView(){
  8176. Row() {
  8177. Button({type:ButtonType.Circle,stateEffect:true}){
  8178. Column() {
  8179. if (this.playType === 0) {
  8180. Image($r('app.media.loop'))
  8181. .width(27)
  8182. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8183. } else if (this.playType === 1) {
  8184. Image($r('app.media.single'))
  8185. .width(27)
  8186. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8187. } else if (this.playType === 2) {
  8188. Image($r('app.media.normal_play'))
  8189. .width(27)
  8190. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8191. } else if (this.playType === 3) {
  8192. Image($r('app.media.random'))
  8193. .width(27)
  8194. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8195. }
  8196. }
  8197. }
  8198. .layoutWeight(1)
  8199. .margin({ left: 5 })
  8200. .backgroundColor(Color.Transparent)
  8201. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8202. .onClick(async () => {
  8203. this.setLoopMode()
  8204. })
  8205. this.fullButton()
  8206. Button({type:ButtonType.Circle,stateEffect:true}){
  8207. Column() {
  8208. Image($r('app.media.lyric'))
  8209. .width(26)
  8210. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8211. }
  8212. }
  8213. .layoutWeight(1)
  8214. .backgroundColor(Color.Transparent)
  8215. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8216. .onClick(async () => {
  8217. this.isLyricSetting = !this.isLyricSetting;
  8218. })
  8219. //播放列表
  8220. Button({type:ButtonType.Circle,stateEffect:true}){
  8221. Image($r('app.media.hm_playlist'))
  8222. .width(24)
  8223. .fillColor(Color.White)
  8224. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8225. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8226. height: '95%',
  8227. dragBar: true,
  8228. showClose: true,
  8229. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8230. blurStyle: BlurStyle.Thin,
  8231. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  8232. title: {
  8233. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8234. + `(${this.songList.length}首)`
  8235. }
  8236. })
  8237. }
  8238. .layoutWeight(1)
  8239. .backgroundColor(Color.Transparent)
  8240. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8241. .onClick(() => {
  8242. this.isShowSheetView = !this.isShowSheetView;
  8243. if(this.isPlayListBgGrass){
  8244. this.isFrontWhite = true
  8245. }else{
  8246. this.isFrontWhite = false
  8247. }
  8248. this.scrollIndex()
  8249. })
  8250. }
  8251. .width(this.isLandscape?'88%':'95%')
  8252. .justifyContent(FlexAlign.SpaceAround)
  8253. .height(30)
  8254. .margin({top:3})
  8255. .animation({
  8256. duration: 666,
  8257. curve: 'ease-in-out' // 可选动画曲线
  8258. })
  8259. }
  8260. @Builder
  8261. fullButton(){
  8262. Button({type:ButtonType.Circle,stateEffect:true}){
  8263. Column() {
  8264. Image($r('app.media.full_4'))
  8265. .width(25)
  8266. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8267. }
  8268. }
  8269. .layoutWeight(1)
  8270. .backgroundColor(Color.Transparent)
  8271. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8272. .onClick(async () => {
  8273. if (this.isLandscape) {
  8274. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8275. } else {
  8276. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8277. }
  8278. })
  8279. }
  8280. //旧版本播放进度条
  8281. @Builder
  8282. playProgressView() {
  8283. Row() {
  8284. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8285. Column() {
  8286. if (this.playType === 0) {
  8287. Image($r('app.media.loop'))
  8288. .width($r('app.float.control_image_width'))
  8289. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8290. } else if (this.playType === 1) {
  8291. Image($r('app.media.single'))
  8292. .width($r('app.float.control_image_width'))
  8293. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8294. } else if (this.playType === 2) {
  8295. Image($r('app.media.normal_play'))
  8296. .width($r('app.float.control_image_width'))
  8297. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8298. } else if (this.playType === 3) {
  8299. Image($r('app.media.random'))
  8300. .width($r('app.float.control_image_width'))
  8301. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8302. }
  8303. }
  8304. }
  8305. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8306. .animation({
  8307. duration: 666,
  8308. curve: 'ease-in-out' // 可选动画曲线
  8309. })
  8310. .backgroundColor(Color.Transparent)
  8311. .margin({ right: 10 })
  8312. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8313. .onClick(async () => {
  8314. this.setLoopMode()
  8315. })
  8316. Text(this.currentTime)
  8317. .fontSize($r('app.float.slider_font_size'))
  8318. .fontColor(Color.White)
  8319. .margin(3)
  8320. Slider({
  8321. value: this.progressValue,
  8322. min: 0,
  8323. max: this.PROGRESS_MAX_VALUE,
  8324. step: 1,
  8325. style: SliderStyle.OutSet
  8326. })
  8327. .width('600px')
  8328. .blockColor('rgba(255,255,255,1)')
  8329. .trackColor('rgba(255,255,255,0.3)')
  8330. .selectedColor(Color.White)
  8331. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  8332. .layoutWeight(1)
  8333. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8334. .showSteps(false)
  8335. .showTips(true)
  8336. .enabled(this.slideEnable)
  8337. .onChange((value: number, mode: SliderChangeMode) => {
  8338. // if (mode == 2) {
  8339. this.isSeekTo = true;
  8340. this.mDestroyPage = false;
  8341. this.showLoadIng();
  8342. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8343. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8344. this.seekTo(seekValue + "");
  8345. // this.setProgress()
  8346. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8347. this.isSeekTo = false;
  8348. // }
  8349. })
  8350. Text(this.totalTime)
  8351. .fontSize($r('app.float.slider_font_size'))
  8352. .fontColor(Color.White)
  8353. .margin(3)
  8354. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8355. //播放列表
  8356. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8357. Image($r('app.media.hm_playlist'))
  8358. .width($r('app.float.control_image_width'))
  8359. .fillColor(Color.White)
  8360. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8361. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8362. height: '95%',
  8363. dragBar: true,
  8364. showClose: true,
  8365. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8366. blurStyle: BlurStyle.Thin,
  8367. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  8368. title: {
  8369. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8370. + `(${this.songList.length}首)`
  8371. }
  8372. })
  8373. }
  8374. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8375. .animation({
  8376. duration: 666,
  8377. curve: 'ease-in-out' // 可选动画曲线
  8378. })
  8379. .backgroundColor(Color.Transparent)
  8380. .margin({ right: 20, left: 10 })
  8381. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8382. .onClick(() => {
  8383. this.isShowSheetView = !this.isShowSheetView;
  8384. if (this.isPlayListBgGrass) {
  8385. this.isFrontWhite = true
  8386. } else {
  8387. this.isFrontWhite = false
  8388. }
  8389. this.scrollIndex()
  8390. })
  8391. }
  8392. //x5的竖屏模式需要99%
  8393. .width(this.isPhonePortrait() ? '93.4%'
  8394. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  8395. .height(this.isPhoneLan() ? 25 : 33)
  8396. .animation({
  8397. duration: 666,
  8398. curve: 'ease-in-out' // 可选动画曲线
  8399. })
  8400. }
  8401. isBigScreen() {
  8402. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  8403. return true
  8404. }
  8405. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8406. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8407. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  8408. return false
  8409. } else {
  8410. return true
  8411. }
  8412. return false
  8413. }
  8414. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  8415. @State isCoverRectangle: boolean = false
  8416. @State isCoverTop: boolean = true
  8417. // 添加控制缩放的状态变量
  8418. @State scaleValueImage: number = 1
  8419. @Builder
  8420. CoverInfo() {
  8421. Column() {
  8422. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  8423. if (this.isCoverRectangle) {
  8424. if (!this.isCoverTop) {
  8425. this.musicNameInfo(false)
  8426. }
  8427. } else {
  8428. this.musicNameInfo(false)
  8429. }
  8430. Stack() {
  8431. // 唱片旋转效果
  8432. Image($r('app.media.ic_music_disc'))
  8433. .width(245)
  8434. .height(245)
  8435. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  8436. .aspectRatio(1)
  8437. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8438. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8439. .borderRadius('100%')
  8440. .align(Alignment.Center)
  8441. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  8442. .rotate({
  8443. angle: this.rotateAngle,
  8444. centerX: "50%",
  8445. centerY: "50%",
  8446. })
  8447. .animation({
  8448. duration: 100,
  8449. curve: Curve.Linear
  8450. })
  8451. .shadow({
  8452. radius: 22,
  8453. type: ShadowType.BLUR,
  8454. color: 'on_primary'
  8455. })
  8456. Column() {
  8457. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  8458. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8459. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  8460. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  8461. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8462. .alt(this.imageLabel)
  8463. .margin({ right: 8, left: 8, top: 8 })
  8464. .aspectRatio(1)
  8465. .opacity(this.opacityValueImage)
  8466. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8467. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8468. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8469. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8470. .align(Alignment.Center)//
  8471. .clip(true)
  8472. .rotate({
  8473. x: 0,
  8474. y: 0,
  8475. z: 1,
  8476. angle: this.rotateAngle
  8477. })
  8478. .shadow({
  8479. radius: 22,
  8480. type: ShadowType.BLUR,
  8481. color: 'on_primary'
  8482. })
  8483. .onClick(() => {
  8484. this.getImageColor()
  8485. })
  8486. this.musicNameInfo(false)
  8487. } else {
  8488. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8489. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  8490. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  8491. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8492. .alt(this.imageLabel)
  8493. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  8494. .aspectRatio(1)
  8495. .opacity(this.opacityValueImage)
  8496. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8497. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8498. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8499. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8500. .align(Alignment.Center)//
  8501. .clip(true)
  8502. .shadow({
  8503. radius: 22,
  8504. type: ShadowType.BLUR,
  8505. color: 'on_primary'
  8506. })
  8507. .rotate({
  8508. x: 0,
  8509. y: 0,
  8510. z: 1,
  8511. angle: this.rotateAngle
  8512. })
  8513. .onClick(() => {
  8514. this.getImageColor()
  8515. })
  8516. if (this.isPhoneLan()) {
  8517. Text(this.name)
  8518. .fontSize(18)
  8519. .fontWeight(FontWeight.Bold)
  8520. .margin({ top: 13 })
  8521. .textOverflow({ overflow: TextOverflow.Ellipsis })
  8522. .maxLines(1)
  8523. .width('99%')
  8524. .textAlign(TextAlign.Center)
  8525. .fontColor(Color.White)
  8526. }
  8527. }
  8528. }
  8529. // 唱针以左上角为点选择逆时针40度
  8530. Image($r('app.media.ic_music_cover_hand'))
  8531. .height(130)
  8532. .margin({ bottom: 220, top: 0 })
  8533. .align(Alignment.Top)
  8534. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  8535. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8536. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8537. Column({ space: 8 }) {
  8538. Text(this.name)
  8539. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  8540. .fontWeight(FontWeight.Bold)
  8541. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8542. .maxLines(1)
  8543. .width('48%')
  8544. .textAlign(TextAlign.Center)
  8545. .fontColor(Color.White)
  8546. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8547. Text(this.artist)
  8548. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  8549. .fontColor(Color.White)
  8550. .fontWeight(FontWeight.Bold)
  8551. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8552. }
  8553. .justifyContent(FlexAlign.Start)
  8554. .zIndex(1)
  8555. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  8556. }
  8557. .margin({
  8558. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  8559. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  8560. top: this.isCoverOpacity() ? 0 : 20
  8561. })
  8562. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  8563. this.SingleLyricView()
  8564. }
  8565. if (this.isPhoneLan()) {
  8566. Column() {
  8567. this.playCenterView()
  8568. // this.playProgressView()
  8569. }
  8570. .position({ left: 28, bottom: 38 })
  8571. } else {
  8572. this.BottomControl()
  8573. }
  8574. }
  8575. .width(CommonConstants.FULL_PERCENT)
  8576. .clip(true)
  8577. }
  8578. @Builder
  8579. private musicNameInfo(isHidden: boolean) {
  8580. Column({ space: 8 }) {
  8581. Text(this.name)
  8582. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  8583. .fontWeight(FontWeight.Bold)
  8584. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8585. .maxLines(1)
  8586. .width('99%')
  8587. .textAlign(TextAlign.Center)
  8588. .fontColor(Color.White)
  8589. Text(this.artist + ' ' + this.currentSong?.album||'')
  8590. .fontSize(this.isCoverOpacity() ? 12 : 15)
  8591. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8592. .fontColor(Color.White)
  8593. .textAlign(TextAlign.Center)
  8594. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  8595. .width('99%')
  8596. .maxLines(1)
  8597. }
  8598. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  8599. .zIndex(1)
  8600. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8601. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  8602. }
  8603. @Builder
  8604. private PlayTitle() {
  8605. Row() {
  8606. Row() {
  8607. Image($r('app.media.ic_back_down'))
  8608. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  8609. .hitTestBehavior(HitTestMode.Transparent)
  8610. Text(this.name + ' ' + this.artist)
  8611. .fontColor(Color.White)
  8612. .fontSize($r('app.float.title_font_size'))
  8613. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8614. .maxLines(1)
  8615. .visibility(Visibility.None)
  8616. .margin({ left: 2, right: 30 })
  8617. }
  8618. .layoutWeight(1)
  8619. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8620. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  8621. .onClick(() => {
  8622. this.isShowPlay = false;
  8623. })
  8624. Column() {
  8625. AVCastPicker({
  8626. normalColor: Color.White,
  8627. onStateChange: this.onStateVastChange
  8628. })
  8629. .width(24)
  8630. .height(24)
  8631. }
  8632. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  8633. }
  8634. .width(PlayConstants.ROW_WIDTH)
  8635. }
  8636. @Builder
  8637. lyricSettingSheet(isPip: boolean) {
  8638. Scroll() {
  8639. this.lyricSetting(isPip)
  8640. }
  8641. .width('100%')
  8642. .height('100%')
  8643. }
  8644. @Builder
  8645. lyricSetting(isPip: boolean) {
  8646. Column() {
  8647. // 时间调节模块
  8648. if (!isPip) {
  8649. this.BuildTimeControls()
  8650. }
  8651. // 字号控制模块
  8652. this.BuildFontControls(isPip)
  8653. }
  8654. }
  8655. // 歌词时间偏移状态
  8656. @State timeOffset: number = 0.0
  8657. @State currentLyricColor: string = '#FFFFFF'
  8658. @State currentLyricColorPip: string = '#FFFFFF'
  8659. @State currentHighLightLyricColor: string = '#FF4081'
  8660. @State currentHighLightLyricColorPip: string = '#FF4081'
  8661. // 歌词字号状态
  8662. @State currentLyricSize: number = 20
  8663. @State currentLyricSizePip: number = 20
  8664. // 高亮歌词放大倍数
  8665. @State currentHightLyricSize: number = 1.2
  8666. @State currentHightLyricSizePip: number = 1.2
  8667. @State currentLyricLineSpace: number = 10
  8668. @State currentLyricLineSpacePip: number = 10
  8669. @State currentLyricAlignMode: number = 1
  8670. @State currentLyricAlignModePip: number = 1
  8671. @State blurDegree: number = 2
  8672. @State blurDegreePip: number = 2
  8673. @State isShowSelectColor: boolean = false
  8674. @State isShowHLSelectColor: boolean = false
  8675. @State isShowPipBgSelectColor: boolean = false
  8676. @State pipLyWidth: number = 330
  8677. @State pipLyHeight: number = 120
  8678. // 构建颜色选择器
  8679. @Builder
  8680. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  8681. Row({ space: 10 }) {
  8682. HSBColorPicker({
  8683. color: '#FFFFFF',
  8684. radius: 8,
  8685. layout: HSBColorPickerLayout.COLUMN,
  8686. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  8687. '#fa7105'],
  8688. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  8689. this.changeLyricColor(value, isPip, isBGPip)
  8690. })
  8691. .height(250)
  8692. .layoutWeight(1)
  8693. .padding(25)
  8694. }
  8695. .width('66%')
  8696. }
  8697. @State isOpenPip: boolean = false
  8698. @State pipBgIndex: number = 0
  8699. // 构建字号控制器
  8700. @Builder
  8701. BuildFontControls(isPip: boolean) {
  8702. Column() {
  8703. if (isPip) {
  8704. Column() {
  8705. Row() {
  8706. Text('悬浮歌词')
  8707. .margin({ left: 18 })
  8708. .fontSize(15)
  8709. .fontColor(Color.White)
  8710. .fontWeight(480)
  8711. .layoutWeight(1)
  8712. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  8713. .selectedColor(this.themeColor)
  8714. .switchPointColor(Color.White)
  8715. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8716. .margin({ right: 18 })
  8717. .onChange((checked: boolean) => {
  8718. this.isOpenPip = checked;
  8719. if (this.isOpenPip) {
  8720. this.startPip()
  8721. } else {
  8722. this.stopPip()
  8723. }
  8724. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  8725. })
  8726. .width(50)
  8727. .height(30);
  8728. }
  8729. .height(55)
  8730. }
  8731. .backgroundColor(Color.Transparent)
  8732. .borderRadius(15)
  8733. .margin({
  8734. left: 30,
  8735. right: 30,
  8736. top: 0,
  8737. bottom: 20
  8738. })
  8739. .padding(0)
  8740. .border({
  8741. color: Color.White,
  8742. width: 1.8
  8743. })
  8744. }else{
  8745. Column() {
  8746. Row() {
  8747. Text('单行歌词')
  8748. .margin({ left: 18 })
  8749. .fontSize(15)
  8750. .fontColor(Color.White)
  8751. .fontWeight(480)
  8752. .layoutWeight(1)
  8753. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  8754. .selectedColor(this.themeColor)
  8755. .switchPointColor(Color.White)
  8756. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8757. .margin({ right: 18 })
  8758. .onChange((checked: boolean) => {
  8759. this.isShowSingleLineLyric = checked;
  8760. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  8761. })
  8762. .width(50)
  8763. .height(30);
  8764. }
  8765. .height(55)
  8766. }
  8767. .backgroundColor(Color.Transparent)
  8768. .borderRadius(15)
  8769. .margin({
  8770. left: 30,
  8771. right: 30,
  8772. top: 10,
  8773. bottom: 10
  8774. })
  8775. .padding(0)
  8776. .border({
  8777. color: Color.White,
  8778. width: 1.8
  8779. })
  8780. }
  8781. Row() {
  8782. Text(`歌词居中:`)
  8783. .fontSize(14)
  8784. .fontColor(Color.White)
  8785. .margin({ left: 2 })
  8786. Row() {
  8787. ForEach(['居中', '居左'], (size: string, index: number) => {
  8788. Button(size)
  8789. .width(60)
  8790. .height(28)
  8791. .fontSize(12)
  8792. .fontColor('#FFFFFF')
  8793. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  8794. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  8795. .border({
  8796. color: (!isPip && this.currentLyricAlignMode === index) ||
  8797. (isPip && this.currentLyricAlignModePip === index) ?
  8798. '#007DFF' : '#DDDDDD',
  8799. width: 1.8
  8800. })
  8801. .onClick(() => {
  8802. this.setLyricAlignMode(index, isPip)
  8803. })
  8804. .margin({ left: 10, right: 8 })
  8805. })
  8806. }
  8807. .width('76%')
  8808. Blank()
  8809. }
  8810. .margin({
  8811. top: 10,
  8812. bottom: 10,
  8813. right: 20,
  8814. left: 20
  8815. })
  8816. if (isPip) {
  8817. Row() {
  8818. Text(`悬浮背景:`)
  8819. .fontSize(14)
  8820. .fontColor(Color.White)
  8821. Select([
  8822. { value: CommonConstants.PIP_LYRIC_BG[0] },
  8823. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  8824. .font({ size: 13, weight: FontWeight.Medium })
  8825. .fontColor(Color.White)
  8826. .margin({ left: 10 })
  8827. .selected(this.pipBgIndex)
  8828. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  8829. .onSelect(async (_index: number, text?: string | undefined) => {
  8830. this.pipBgIndex = _index
  8831. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  8832. if (this.pipBgIndex === 0) {
  8833. if (this.cover) {
  8834. this.pipBg = this.cover
  8835. } else {
  8836. this.pipBg = this.imageColor
  8837. }
  8838. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8839. } else {
  8840. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8841. }
  8842. })
  8843. Column() {
  8844. }
  8845. .backgroundColor(this.pipBg)
  8846. .margin({ left: 10, right: 10 })
  8847. .borderRadius(20)
  8848. .height(28)
  8849. .width(28)
  8850. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8851. Row() {
  8852. SymbolGlyph($r('sys.symbol.paintbrush'))
  8853. .fontColor([Color.White])
  8854. .effectStrategy(1)
  8855. Text(`选择颜色`)
  8856. .fontSize(13)
  8857. .margin({ left: 10 })
  8858. .fontColor(Color.White)
  8859. }
  8860. }
  8861. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  8862. .backgroundColor(Color.Transparent)
  8863. .border({
  8864. color: '#FFFFFF',
  8865. radius: 20,
  8866. width: 1.8
  8867. })
  8868. .height(36)
  8869. .width(110)
  8870. .onClick(() => {
  8871. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  8872. })
  8873. .bindPopup(this.isShowPipBgSelectColor, {
  8874. builder: this.SelectColor(false, isPip, true),
  8875. placement: Placement.Top,
  8876. mask: { color: '#33000000' },
  8877. enableArrow: false, //是否显示箭头
  8878. showInSubWindow: false,
  8879. onStateChange: (e) => {
  8880. if (!e.isVisible) {
  8881. this.isShowPipBgSelectColor = false
  8882. }
  8883. }
  8884. })
  8885. }
  8886. .width('76%')
  8887. .margin({ bottom: 5, right: 45, left: 20 })
  8888. }
  8889. if (!isPip) {
  8890. Row() {
  8891. Text(`高亮居中:`)
  8892. .fontSize(14)
  8893. .fontColor(Color.White)
  8894. Column() {
  8895. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  8896. .selectedColor(this.themeColor)
  8897. .switchPointColor(Color.White)
  8898. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8899. .onChange((checked: boolean) => {
  8900. this.isHightLightCenter = checked;
  8901. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  8902. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8903. })
  8904. .width(50)
  8905. .height(30)
  8906. .alignSelf(ItemAlign.Start)
  8907. .margin({ left: 12 })
  8908. Blank()
  8909. }
  8910. .width('76%')
  8911. }
  8912. .margin({
  8913. left: 20,
  8914. right: 15,
  8915. top: 10,
  8916. bottom: 10
  8917. })
  8918. }
  8919. Row() {
  8920. Text(`歌词颜色:`)
  8921. .fontSize(14)
  8922. .fontColor(Color.White)
  8923. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8924. .fontSize(15)
  8925. .fontColor(Color.White)
  8926. .margin({ left: 12, right: 12 })
  8927. Column() {
  8928. }
  8929. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8930. .margin({ right: 12 })
  8931. .borderRadius(20)
  8932. .height(28)
  8933. .width(28)
  8934. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8935. Row() {
  8936. SymbolGlyph($r('sys.symbol.paintbrush'))
  8937. .fontColor([Color.White])
  8938. .effectStrategy(1)
  8939. Text(`选择颜色`)
  8940. .fontSize(13)
  8941. .margin({ left: 10 })
  8942. .fontColor(Color.White)
  8943. }
  8944. }
  8945. .backgroundColor(Color.Transparent)
  8946. .border({
  8947. color: '#FFFFFF',
  8948. radius: 20,
  8949. width: 1.8
  8950. })
  8951. .height(36)
  8952. .width(110)
  8953. .onClick(() => {
  8954. this.isShowSelectColor = !this.isShowSelectColor
  8955. })
  8956. .bindPopup(this.isShowSelectColor, {
  8957. builder: this.SelectColor(false, isPip),
  8958. placement: Placement.Top,
  8959. mask: { color: '#33000000' },
  8960. enableArrow: false, //是否显示箭头
  8961. showInSubWindow: false,
  8962. onStateChange: (e) => {
  8963. if (!e.isVisible) {
  8964. this.isShowSelectColor = false
  8965. }
  8966. }
  8967. })
  8968. }
  8969. .width('76%')
  8970. .margin({
  8971. top: 10,
  8972. bottom: 10,
  8973. right: 45,
  8974. left: 20
  8975. })
  8976. Row() {
  8977. Text(`高亮颜色:`)
  8978. .fontSize(14)
  8979. .fontColor(Color.White)
  8980. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8981. .fontSize(15)
  8982. .fontColor(Color.White)
  8983. .margin({ left: 12, right: 12 })
  8984. Column() {
  8985. }
  8986. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8987. .margin({ right: 12 })
  8988. .borderRadius(20)
  8989. .height(28)
  8990. .width(28)
  8991. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8992. Row() {
  8993. SymbolGlyph($r('sys.symbol.paintbrush'))
  8994. .fontColor([Color.White])
  8995. .effectStrategy(1)
  8996. Text(`选择颜色`)
  8997. .fontSize(13)
  8998. .margin({ left: 10 })
  8999. .fontColor(Color.White)
  9000. }
  9001. }
  9002. .backgroundColor(Color.Transparent)
  9003. .border({
  9004. color: '#FFFFFF',
  9005. radius: 20,
  9006. width: 1.8
  9007. })
  9008. .height(36)
  9009. .width(110)
  9010. .onClick(() => {
  9011. this.isShowHLSelectColor = !this.isShowHLSelectColor
  9012. })
  9013. .bindPopup(this.isShowHLSelectColor, {
  9014. builder: this.SelectColor(true, isPip),
  9015. placement: Placement.Top,
  9016. mask: { color: '#33000000' },
  9017. enableArrow: false, //是否显示箭头
  9018. showInSubWindow: false,
  9019. onStateChange: (e) => {
  9020. if (!e.isVisible) {
  9021. this.isShowHLSelectColor = false
  9022. }
  9023. }
  9024. })
  9025. }
  9026. .width('76%')
  9027. .margin({
  9028. top: 10,
  9029. bottom: 10,
  9030. right: 45,
  9031. left: 20
  9032. })
  9033. if (isPip) {
  9034. Row() {
  9035. Text(`显示宽度:`)
  9036. .fontSize(14)
  9037. .fontColor(Color.White)
  9038. Slider({
  9039. value: this.pipLyWidth,
  9040. min: 10,
  9041. max: 800,
  9042. step: 1,
  9043. style: SliderStyle.OutSet
  9044. })
  9045. .blockColor(this.themeColor)
  9046. .trackColor($r('app.color.speed_text_color'))
  9047. .selectedColor(Color.White)
  9048. .trackThickness(6)
  9049. .onChange((value: number) => {
  9050. this.pipLyWidth = value
  9051. if (this.pipController) {
  9052. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9053. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  9054. }
  9055. })
  9056. .width('76%')
  9057. }
  9058. .margin({
  9059. left: 20,
  9060. right: 15,
  9061. top: 5,
  9062. bottom: 5
  9063. })
  9064. Row() {
  9065. Text(`显示高度:`)
  9066. .fontSize(14)
  9067. .fontColor(Color.White)
  9068. Slider({
  9069. value: this.pipLyHeight,
  9070. min: 10,
  9071. max: 1000,
  9072. step: 1,
  9073. style: SliderStyle.OutSet
  9074. })
  9075. .blockColor(this.themeColor)
  9076. .trackColor($r('app.color.speed_text_color'))
  9077. .selectedColor(Color.White)
  9078. .trackThickness(6)
  9079. .onChange((value: number) => {
  9080. this.pipLyHeight = value
  9081. if (this.pipController) {
  9082. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9083. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  9084. }
  9085. })
  9086. .width('76%')
  9087. }
  9088. .margin({
  9089. left: 20,
  9090. right: 15,
  9091. top: 5,
  9092. bottom: 5
  9093. })
  9094. }
  9095. Row() {
  9096. Text(`歌词字号:`)
  9097. .fontSize(14)
  9098. .fontColor(Color.White)
  9099. Slider({
  9100. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  9101. min: 12,
  9102. max: 30,
  9103. step: 0.1,
  9104. style: SliderStyle.OutSet
  9105. })
  9106. .blockColor(this.themeColor)
  9107. .trackColor($r('app.color.speed_text_color'))
  9108. .selectedColor(Color.White)
  9109. .trackThickness(6)
  9110. .onChange((value: number) => {
  9111. this.setLyricTextSize(value, isPip)
  9112. })
  9113. .width('76%')
  9114. }
  9115. .margin({
  9116. left: 20,
  9117. right: 15,
  9118. top: 5,
  9119. bottom: 5
  9120. })
  9121. Row() {
  9122. Text(`高亮倍数:`)
  9123. .fontSize(14)
  9124. .fontColor(Color.White)
  9125. Slider({
  9126. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  9127. min: 1,
  9128. max: 2,
  9129. step: 0.1,
  9130. style: SliderStyle.OutSet
  9131. })
  9132. .blockColor(this.themeColor)
  9133. .trackColor($r('app.color.speed_text_color'))
  9134. .selectedColor(Color.White)
  9135. .trackThickness(6)
  9136. .onChange((value: number) => {
  9137. this.setHighLyricTextSize(value, isPip)
  9138. })
  9139. .width('76%')
  9140. }
  9141. .margin({
  9142. left: 20,
  9143. right: 15,
  9144. top: 5,
  9145. bottom: 5
  9146. })
  9147. Row() {
  9148. Text(`歌词间隙:`)
  9149. .fontSize(14)
  9150. .fontColor(Color.White)
  9151. Slider({
  9152. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  9153. min: 0,
  9154. max: 100,
  9155. step: 1,
  9156. style: SliderStyle.OutSet
  9157. })
  9158. .blockColor(this.themeColor)
  9159. .trackColor($r('app.color.speed_text_color'))
  9160. .selectedColor(Color.White)
  9161. .trackThickness(6)
  9162. .onChange((value: number) => {
  9163. this.setLyricLineSpace(value, isPip)
  9164. })
  9165. .width('76%')
  9166. }
  9167. .margin({
  9168. left: 20,
  9169. right: 15,
  9170. top: 5,
  9171. bottom: 5
  9172. })
  9173. //取值间隔为100,默认为400,取值越大,字体越粗
  9174. Row() {
  9175. Text(`歌词字重:`)
  9176. .fontSize(14)
  9177. .fontColor(Color.White)
  9178. Slider({
  9179. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  9180. min: 100,
  9181. max: 900,
  9182. step: 100,
  9183. style: SliderStyle.OutSet
  9184. })
  9185. .blockColor(this.themeColor)
  9186. .trackColor($r('app.color.speed_text_color'))
  9187. .selectedColor(Color.White)
  9188. .trackThickness(6)
  9189. .onChange((value: number) => {
  9190. if (isPip) {
  9191. this.lyricTextWeightPip = value
  9192. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9193. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  9194. } else {
  9195. this.lyricTextWeight = value
  9196. this.lyricController.setTextWeight(this.lyricTextWeight)
  9197. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  9198. }
  9199. })
  9200. .width('76%')
  9201. }
  9202. .margin({
  9203. left: 20,
  9204. right: 15,
  9205. top: 5,
  9206. bottom: 5
  9207. })
  9208. if (!isPip) {
  9209. Row() {
  9210. Text(`歌词模糊:`)
  9211. .fontSize(14)
  9212. .fontColor(Color.White)
  9213. Slider({
  9214. value: isPip ? this.blurDegreePip : this.blurDegree,
  9215. min: 0,
  9216. max: 5,
  9217. step: 0.1,
  9218. style: SliderStyle.OutSet
  9219. })
  9220. .blockColor(this.themeColor)
  9221. .trackColor($r('app.color.speed_text_color'))
  9222. .selectedColor(Color.White)
  9223. .trackThickness(6)
  9224. .onChange((value: number) => {
  9225. this.setBlurDegree(value, isPip)
  9226. })
  9227. .width('76%')
  9228. }
  9229. .margin({
  9230. left: 20,
  9231. right: 15,
  9232. top: 5,
  9233. bottom: 15
  9234. })
  9235. }
  9236. Row() {
  9237. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  9238. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  9239. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  9240. }
  9241. .justifyContent(FlexAlign.Center)
  9242. .margin({ top: 3, bottom: 10 })
  9243. }
  9244. }
  9245. private setBlurDegree(index: number, isPip: boolean) {
  9246. if (isPip) {
  9247. this.blurDegreePip = index
  9248. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  9249. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  9250. } else {
  9251. this.blurDegree = index
  9252. this.lyricController.setBlurDegree(this.blurDegree)
  9253. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  9254. }
  9255. }
  9256. private setLyricAlignMode(index: number, isPip: boolean) {
  9257. if (isPip) {
  9258. this.currentLyricAlignModePip = index
  9259. if (this.currentLyricAlignModePip === 1) {
  9260. this.lyricControllerXF.setAlignMode("left")
  9261. } else {
  9262. this.lyricControllerXF.setAlignMode("center")
  9263. }
  9264. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  9265. } else {
  9266. this.currentLyricAlignMode = index
  9267. if (this.currentLyricAlignMode === 1) {
  9268. this.lyricController.setAlignMode("left")
  9269. } else {
  9270. this.lyricController.setAlignMode("center")
  9271. }
  9272. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  9273. }
  9274. }
  9275. private setLyricTextSize(index: number, isPip: boolean) {
  9276. if (isPip) {
  9277. this.currentLyricSizePip = index
  9278. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  9279. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  9280. } else {
  9281. this.currentLyricSize = index
  9282. this.lyricController.setTextSize(this.currentLyricSize)
  9283. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  9284. }
  9285. }
  9286. private setHighLyricTextSize(scale: number, isPip: boolean) {
  9287. if (isPip) {
  9288. this.currentHightLyricSizePip = scale
  9289. this.lyricControllerXF
  9290. .setHighlightScale(this.currentHightLyricSizePip)
  9291. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  9292. } else {
  9293. this.currentHightLyricSize = scale
  9294. this.lyricController
  9295. .setHighlightScale(this.currentHightLyricSize)
  9296. PreferencesUtil.putSync('HighLyricTextSize', scale)
  9297. }
  9298. }
  9299. private setLyricLineSpace(index: number, isPip: boolean) {
  9300. if (isPip) {
  9301. this.currentLyricLineSpacePip = index
  9302. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  9303. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  9304. } else {
  9305. this.currentLyricLineSpace = index
  9306. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  9307. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  9308. }
  9309. }
  9310. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  9311. LogUtil.info('onecold isBG = ' + isBG)
  9312. if (isBG) { //如果是设置悬浮背景
  9313. this.pipBg = color
  9314. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  9315. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9316. return
  9317. }
  9318. if (isPip) {
  9319. this.currentLyricColorPip = color
  9320. this.lyricControllerXF
  9321. .setTextColor(this.currentLyricColorPip)
  9322. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  9323. } else {
  9324. this.currentLyricColor = color
  9325. this.lyricController
  9326. .setTextColor(this.currentLyricColor)
  9327. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  9328. }
  9329. }
  9330. private changeLyricHightLightColor(color: string, isPip: boolean) {
  9331. if (isPip) {
  9332. this.currentHighLightLyricColorPip = color
  9333. this.lyricControllerXF
  9334. .setHighlightColor(this.currentHighLightLyricColorPip)
  9335. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  9336. } else {
  9337. this.currentHighLightLyricColor = color
  9338. this.lyricController
  9339. .setHighlightColor(this.currentHighLightLyricColor)
  9340. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  9341. }
  9342. }
  9343. // 构建时间控制器
  9344. @Builder
  9345. BuildTimeControls() {
  9346. Column() {
  9347. // 时间显示
  9348. Text(this.getTimeText())
  9349. .fontSize(18)
  9350. .fontColor(Color.White)
  9351. .margin({ bottom: 10 })
  9352. Row() {
  9353. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  9354. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  9355. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  9356. }
  9357. .justifyContent(FlexAlign.Center)
  9358. }
  9359. .margin({ top: 12, bottom: 8 })
  9360. }
  9361. // 精度按钮组件
  9362. @Builder
  9363. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  9364. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9365. Column() {
  9366. Image(icon)
  9367. .width(28)
  9368. .margin({ bottom: 5 })
  9369. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  9370. Text(label)
  9371. .fontSize(12)
  9372. .fontColor('#FFFFFF')
  9373. }
  9374. }
  9375. .backgroundColor(Color.Transparent)
  9376. .enabled(!this.isButtonDisabled(step))
  9377. .onClick(() => this.handlePrecisionAdjust(step))
  9378. .padding(5)
  9379. .width(66)
  9380. .height(66)
  9381. .margin({ left: 18, right: 18 })
  9382. .border({
  9383. color: '#FFFFFF',
  9384. width: 1.8
  9385. })
  9386. }
  9387. private handlePrecisionAdjust(step: number) {
  9388. if (step === 0) {
  9389. this.timeOffset = 0
  9390. return
  9391. }
  9392. // 精度处理:保留1位小数
  9393. const newOffset = Number((this.timeOffset + step).toFixed(5))
  9394. // 边界保护(±15.0秒)
  9395. if (newOffset < -30.0 || newOffset > 30.0) {
  9396. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  9397. return
  9398. }
  9399. // 状态更新
  9400. this.timeOffset = newOffset
  9401. }
  9402. // 按钮禁用逻辑
  9403. private isButtonDisabled(step: number): boolean {
  9404. const futureOffset = this.timeOffset + step
  9405. return (futureOffset < -30.0) || (futureOffset > 30.0)
  9406. }
  9407. // 时间显示文本升级
  9408. private getTimeText(): string {
  9409. const absValue = Math.abs(this.timeOffset)
  9410. return this.timeOffset === 0
  9411. ? '歌词时间已重置'
  9412. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  9413. }
  9414. // 导入 本地歌词 搜索歌词
  9415. @Builder
  9416. pushLyricButton(icon: Resource, step: number, label: string) {
  9417. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9418. Row() {
  9419. Image(icon)
  9420. .width(14)
  9421. .margin({ left: 13 })
  9422. Text(label)
  9423. .fontSize(12)
  9424. .margin({ left: 6 })
  9425. .fontColor('#FFFFFF')
  9426. }
  9427. }
  9428. .onClick(() => {
  9429. switch (step) {
  9430. case 0:
  9431. this.callFilePickerSelectFileForLyric()
  9432. break;
  9433. case 1:
  9434. //判断有没有设置api
  9435. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  9436. this.isLyricSetting = false
  9437. this.showTipsDialog()
  9438. return
  9439. }
  9440. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9441. ToastUtil.showToast('正在获取')
  9442. this.isLyricSetting = false
  9443. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9444. this.initLyric(lyricPath, true);
  9445. }
  9446. break;
  9447. }
  9448. })
  9449. .padding(5)
  9450. .width(110)
  9451. .backgroundColor(Color.Transparent)
  9452. .height(40)
  9453. .margin({ left: 6, right: 6 })
  9454. .border({
  9455. color: '#FFFFFF',
  9456. radius: 20,
  9457. width: 1.8
  9458. })
  9459. }
  9460. showVipDialog() {
  9461. DialogHelper.showCustomContentDialog({
  9462. dialogId: 'vip',
  9463. title: "友情提示",
  9464. autoCancel: false, //点击遮障层时,不关闭弹窗
  9465. backCancel: true, //点击返回键,不关闭弹窗
  9466. contentBuilder: () => {
  9467. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  9468. },
  9469. buttons: [],
  9470. })
  9471. }
  9472. //去赞助的自定义内容
  9473. @Builder
  9474. customVipBuilder(content: string) {
  9475. Column() {
  9476. Text(content)
  9477. .fontColor(Color.Gray)
  9478. .fontSize(16)
  9479. .alignSelf(ItemAlign.Start)
  9480. .margin({ bottom: 15 })
  9481. .fontSize(16)
  9482. Row() {
  9483. Button('取消')
  9484. .fontColor(Color.White)
  9485. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9486. .height(50)
  9487. .layoutWeight(1)
  9488. .stateEffect(true)
  9489. .margin({ right: 6 })
  9490. .onClick(() => {
  9491. DialogHelper.closeDialog('vip'); //关闭弹框
  9492. })
  9493. Button('开通')
  9494. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9495. .layoutWeight(1)
  9496. .height(50)
  9497. .backgroundColor(this.themeColor)
  9498. .stateEffect(true)
  9499. .margin({ left: 6 })
  9500. .onClick(() => {
  9501. DialogHelper.closeDialog('vip'); //关闭弹框
  9502. this.isShowPlay = false
  9503. this.mType = 1 //跳转到用户中心
  9504. // router.pushUrl({
  9505. // url: 'pages/VipPage'
  9506. // }, router.RouterMode.Single);
  9507. })
  9508. }
  9509. }
  9510. .width("100%")
  9511. .padding(10)
  9512. }
  9513. showTipsDialog() {
  9514. DialogHelper.showCustomContentDialog({
  9515. dialogId: 'tips',
  9516. title: "友情提示",
  9517. autoCancel: false, //点击遮障层时,不关闭弹窗
  9518. backCancel: true, //点击返回键,不关闭弹窗
  9519. contentBuilder: () => {
  9520. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  9521. },
  9522. buttons: [],
  9523. })
  9524. }
  9525. @Builder
  9526. customTipsBuilder(content: string) {
  9527. Column() {
  9528. Text(content)
  9529. .fontColor(Color.Gray)
  9530. .fontSize(16)
  9531. .alignSelf(ItemAlign.Start)
  9532. .margin({ bottom: 15 })
  9533. .fontSize(16)
  9534. Row() {
  9535. Button('取消')
  9536. .fontColor(Color.White)
  9537. .backgroundColor(this.themeColor)
  9538. .height(50)
  9539. .layoutWeight(1)
  9540. .stateEffect(true)
  9541. .margin({ right: 6 })
  9542. .onClick(() => {
  9543. DialogHelper.closeDialog('tips'); //关闭弹框
  9544. })
  9545. Button('跳转')
  9546. .fontColor(Color.White)//
  9547. .layoutWeight(1)
  9548. .height(50)
  9549. .backgroundColor(this.themeColor)
  9550. .stateEffect(true)
  9551. .margin({ left: 6 })
  9552. .onClick(() => {
  9553. DialogHelper.closeDialog('tips'); //关闭弹框
  9554. this.isShowEdit = false
  9555. this.longItemFilePath = ''
  9556. // if(this.isGridMusic&&!this.isShowPlay){
  9557. // this.longItemFilePath== ''
  9558. // }else{
  9559. // this.isShowEdit = false
  9560. // }
  9561. this.isShowMoreView = false;
  9562. this.isShowPlay = false
  9563. this.mType = 4
  9564. // router.pushUrl({
  9565. // url: 'pages/SettingPage'
  9566. // }, router.RouterMode.Single);
  9567. })
  9568. }
  9569. }
  9570. .width("100%")
  9571. .padding(10)
  9572. }
  9573. @Builder
  9574. PlayMoreSheet() {
  9575. Column() {
  9576. this.MoreList()
  9577. }
  9578. .width('100%')
  9579. .height('100%')
  9580. }
  9581. @Builder
  9582. MoreList() {
  9583. Scroll() {
  9584. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9585. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  9586. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9587. Row() {
  9588. if (more.id === 3&&this.currentSong) {
  9589. Image(more.image)
  9590. .width(24)
  9591. .height(24)
  9592. .margin({ left: 10, right: 10 })
  9593. Text(more.title)
  9594. .fontSize(16)
  9595. .fontColor(Color.White)
  9596. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  9597. height: this.isCoverOpacity() ? '95%' : '95%',
  9598. dragBar: true,
  9599. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9600. showClose: true,
  9601. blurStyle: BlurStyle.Thin,
  9602. backgroundColor: Color.Transparent,
  9603. title: { title: '歌曲信息' }
  9604. })
  9605. } else if (more.id === 15 && this.currentSong) { //编辑标签
  9606. Image(more.image)
  9607. .width(24)
  9608. .height(24)
  9609. .margin({ left: 10, right: 10 })
  9610. Text(more.title)
  9611. .fontSize(16)
  9612. .fontColor(Color.White)
  9613. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9614. height: '99%',
  9615. dragBar: true,
  9616. showClose: true,
  9617. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9618. // blurStyle:BlurStyle.Thin,
  9619. // backgroundColor:Color.Transparent,
  9620. title: { title: '编辑标签' }
  9621. })
  9622. } else if (more.id === 5) { //定时关闭
  9623. Image(more.image)
  9624. .width(24)
  9625. .height(24)
  9626. .margin({ left: 10, right: 10 })
  9627. Text(more.title)
  9628. .fontSize(16)
  9629. .fontColor(Color.White)
  9630. .onClick(() => {
  9631. this.doMore(more.id)
  9632. })
  9633. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  9634. height: this.isCoverOpacity() ? '95%' : '95%',
  9635. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9636. dragBar: true,
  9637. showClose: true,
  9638. title: { title: $r('app.string.time_close') }
  9639. })
  9640. } else if (more.id === 2) { //歌词设置
  9641. Image(more.image)
  9642. .width(24)
  9643. .height(24)
  9644. .margin({ left: 10, right: 10 })
  9645. Text(more.title)
  9646. .fontSize(16)
  9647. .fontColor(Color.White)
  9648. } else if (more.id === 16) { //悬浮歌词设置
  9649. Image(more.image)
  9650. .width(24)
  9651. .height(24)
  9652. .margin({ left: 10, right: 10 })
  9653. Text(more.title)
  9654. .fontSize(16)
  9655. .fontColor(Color.White)
  9656. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  9657. height: this.isCoverOpacity() ? '95%' : '95%',
  9658. dragBar: true,
  9659. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9660. showClose: true,
  9661. blurStyle: BlurStyle.Thin,
  9662. backgroundColor: Color.Transparent,
  9663. title: { title: '悬浮歌词' }
  9664. })
  9665. } else if (more.id === 11) {
  9666. Image(more.image)
  9667. .width(24)
  9668. .height(24)
  9669. .margin({ left: 10, right: 10 })
  9670. Text(more.title)
  9671. .fontSize(16)
  9672. .fontColor(Color.White)
  9673. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  9674. height: this.isCoverOpacity() ? '95%' : '60%',
  9675. dragBar: true,
  9676. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9677. showClose: true,
  9678. blurStyle: BlurStyle.Thin,
  9679. backgroundColor: Color.Transparent,
  9680. title: { title: '跳过头尾' }
  9681. })
  9682. } else if (more.id === 12) { //投播
  9683. AVCastPicker({
  9684. customPicker: (): void => this.TPImageBuilder(more),
  9685. onStateChange: (state) => {
  9686. if (state == AVCastPickerState.STATE_APPEARING) {
  9687. console.log(' The picker starts showing.');
  9688. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  9689. console.log(' The picker finishes presenting.');
  9690. }
  9691. },
  9692. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  9693. sessionType: 'video'
  9694. })
  9695. .id('AVCastPicker')
  9696. } else {
  9697. Image(more.image)
  9698. .width(24)
  9699. .height(24)
  9700. .margin({ left: 10, right: 10 })
  9701. .onClick(() => {
  9702. this.doMore(more.id)
  9703. })
  9704. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  9705. .fontSize(16)
  9706. .fontColor(Color.White)
  9707. .onClick(() => {
  9708. this.doMore(more.id)
  9709. })
  9710. Select([//倍速
  9711. { value: '0.25x' },
  9712. { value: '0.5x' },
  9713. { value: '0.75x' },
  9714. { value: '1x' },
  9715. { value: '1.25x' },
  9716. { value: '1.5x' },
  9717. { value: '1.75x' },
  9718. { value: '2x' },
  9719. { value: '3x' }])
  9720. .font({ size: 16, weight: FontWeight.Medium })
  9721. .fontColor($r('sys.color.white'))
  9722. .margin({ left: 25 })
  9723. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  9724. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  9725. .value(Utility.optimizedFormat(this.playSpeed))
  9726. .onSelect(async (_index: number, text?: string | undefined) => {
  9727. let speed = parseFloat(text?.replace('x', '') || '1');
  9728. if (!CommonConstants.video_speed_list.includes(speed)) {
  9729. speed = 1;
  9730. }
  9731. this.playSpeed = speed
  9732. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9733. })
  9734. Slider({
  9735. value: this.volume,
  9736. min: 0,
  9737. max: 1,
  9738. step: 0.1,
  9739. style: SliderStyle.OutSet
  9740. })
  9741. .margin({ left: 18, right: 8 })
  9742. .blockColor(this.themeColor)
  9743. .trackColor($r('app.color.speed_text_color'))
  9744. .selectedColor(Color.White)
  9745. .trackThickness(9)
  9746. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  9747. .onChange((value: number) => {
  9748. this.volume = value;
  9749. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9750. PreferencesUtil.putSync('DefalutVolume',this.volume)
  9751. })
  9752. .layoutWeight(1)
  9753. Blank()
  9754. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  9755. .selectedColor(this.themeColor)
  9756. .switchPointColor(Color.White)
  9757. .margin({ right: 15 })
  9758. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9759. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  9760. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9761. if (more.id == 6) {
  9762. this.isMusicMemoryPlay = checked;
  9763. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  9764. if (this.isMusicMemoryPlay) {
  9765. ToastUtil.showToast('记忆播放已开启')
  9766. } else {
  9767. ToastUtil.showToast('记忆播放已关闭')
  9768. }
  9769. }
  9770. })
  9771. .width(48)
  9772. .height(24);
  9773. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  9774. .selectedColor(this.themeColor)
  9775. .switchPointColor(Color.White)
  9776. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9777. .margin({ right: 15 })
  9778. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  9779. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9780. if (more.id == 7) {
  9781. this.isMusicBGCover = checked;
  9782. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  9783. if (this.isMusicBGCover) {
  9784. ToastUtil.showToast('播放背景随音乐封面已开启')
  9785. } else {
  9786. ToastUtil.showToast('播放背景随音乐封面已关闭')
  9787. }
  9788. }
  9789. })
  9790. .width(48)
  9791. .height(24);
  9792. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  9793. .selectedColor(this.themeColor)
  9794. .switchPointColor(Color.White)
  9795. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9796. .margin({ right: 15 })
  9797. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  9798. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9799. if (more.id == 8) {
  9800. this.isSavePlayMode = checked;
  9801. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  9802. if (this.isSavePlayMode) {
  9803. ToastUtil.showToast('保存播放模式已开启')
  9804. } else {
  9805. ToastUtil.showToast('保存播放模式已关闭')
  9806. }
  9807. }
  9808. })
  9809. .width(48)
  9810. .height(24);
  9811. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  9812. .selectedColor(this.themeColor)
  9813. .switchPointColor(Color.White)
  9814. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9815. .margin({ right: 15 })
  9816. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  9817. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9818. if (more.id == 13) {
  9819. this.isCoverRectangle = checked;
  9820. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  9821. if (this.isCoverRectangle) {
  9822. ToastUtil.showToast('封面方形已开启')
  9823. this.animationRoFun()
  9824. } else {
  9825. ToastUtil.showToast('封面圆形已开启')
  9826. this.animationRoFun()
  9827. }
  9828. }
  9829. })
  9830. .width(48)
  9831. .height(24);
  9832. }
  9833. }
  9834. .width('100%')
  9835. .height(45)
  9836. .padding(15)
  9837. .backgroundColor(Color.Transparent)
  9838. .borderRadius(12)
  9839. .margin({ bottom: 6 })
  9840. }
  9841. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  9842. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  9843. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  9844. .backgroundColor(Color.Transparent)
  9845. .onClick(() => {
  9846. this.doMore(more.id)
  9847. })
  9848. });
  9849. }
  9850. .width('100%')
  9851. .padding(16)
  9852. }.margin({ bottom: 18 })
  9853. }
  9854. @Builder
  9855. TPImageBuilder(more: MoreItem): void {
  9856. Row() {
  9857. Image($r('app.media.tuoping'))
  9858. .width(22)
  9859. .height(22)
  9860. .margin({ left: 10, right: 10 })
  9861. Text(more.title)
  9862. .fontSize(16)
  9863. .fontColor(Color.White)
  9864. }
  9865. .width('100%')
  9866. .layoutWeight(1)
  9867. .alignItems(VerticalAlign.Center)
  9868. .justifyContent(FlexAlign.Start)
  9869. }
  9870. private moreItems: MoreItem[] = [
  9871. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  9872. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  9873. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  9874. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  9875. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  9876. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  9877. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  9878. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  9879. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  9880. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  9881. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  9882. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  9883. { id: 4, image: $r('app.media.share2'), title: '分享' },
  9884. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  9885. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  9886. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  9887. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  9888. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  9889. ];
  9890. @State isShowMoreView: boolean = false;
  9891. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  9892. @State isShowTimeCloseMore: boolean = false
  9893. @State isShowDetailMore: boolean = false
  9894. @State isMusicBGCover: boolean = true
  9895. @State isSavePlayMode: boolean = true
  9896. @State isLyricSetting: boolean = false
  9897. @State isJumpSetting: boolean = false
  9898. @State isShowEdit: boolean = false
  9899. @State showPipLyric: boolean = false
  9900. async setRingTone() {
  9901. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  9902. return
  9903. }
  9904. // 确定后的逻辑
  9905. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  9906. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  9907. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  9908. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  9909. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  9910. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  9911. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  9912. , this.videoUrl, this.name).then(res => {
  9913. LogUtil.info('onecold setFlag :' + res);
  9914. });
  9915. }
  9916. doMore(moreId: number) {
  9917. switch (moreId) {
  9918. case 2: //歌词
  9919. this.isLyricSetting = !this.isLyricSetting;
  9920. this.isShowMoreView = false
  9921. break;
  9922. case 3: //详情
  9923. this.isShowDetailMore = !this.isShowDetailMore;
  9924. break;
  9925. case 4: //分享
  9926. if (this.currentSong !== undefined) {
  9927. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  9928. }
  9929. this.isShowMoreView = false
  9930. break;
  9931. case 5: //定时关闭
  9932. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  9933. break;
  9934. case 10: //设为铃声
  9935. this.setRingTone()
  9936. this.isShowMoreView = false
  9937. break;
  9938. case 11: //跳过头尾
  9939. this.isJumpSetting = !this.isJumpSetting;
  9940. break;
  9941. case 13: //倍速
  9942. break;
  9943. case 14: //搜索封面
  9944. if (this.currentSong !== undefined) {
  9945. this.doSearchCover(this.currentSong)
  9946. }
  9947. this.isShowMoreView = false
  9948. break;
  9949. case 15: //编辑标签
  9950. this.setEditStrEmpty()
  9951. this.tempLyricContent = this.lyricContent
  9952. this.isShowEdit = !this.isShowEdit;
  9953. break;
  9954. case 16: //悬浮歌词
  9955. this.showPipLyric = !this.showPipLyric;
  9956. break;
  9957. case 17: //横屏模式
  9958. if (this.isLandscape) {
  9959. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9960. } else {
  9961. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9962. }
  9963. this.isShowMoreView = false
  9964. break;
  9965. case 20://AB循环
  9966. this.isABSheet = !this.isABSheet
  9967. break;
  9968. }
  9969. }
  9970. //AB循环
  9971. @State isOpenAB:boolean = false
  9972. @State jumpATime:number = 0
  9973. @State jumpBTime:number = 0
  9974. @State isABSheet:boolean = false
  9975. @Builder
  9976. ABLoopSheet() {
  9977. ABLoopComptent({
  9978. jumpATime:this.jumpATime,
  9979. jumpBTime:this.jumpBTime,
  9980. onClickAItem: async ()=>{
  9981. if(this.mIjkMediaPlayer){
  9982. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  9983. }
  9984. },
  9985. onClickBItem: async ()=>{
  9986. if(this.mIjkMediaPlayer){
  9987. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  9988. if(this.jumpBTime<=this.jumpATime){
  9989. ToastUtil.showToast('设置B点时间不能小于A点时间')
  9990. this.jumpBTime = 0
  9991. }
  9992. }
  9993. },
  9994. onCancleButtonClick: async ()=>{
  9995. this.isOpenAB = false
  9996. this.isABSheet = false
  9997. },
  9998. onStartButtonClick: async ()=>{
  9999. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  10000. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  10001. return
  10002. }
  10003. this.isABSheet = false
  10004. this.startABLoop()
  10005. },
  10006. })
  10007. }
  10008. //开始AB循环
  10009. startABLoop(){
  10010. if(this.mIjkMediaPlayer){
  10011. this.seekTo(this.jumpATime+'')
  10012. this.isOpenAB = true
  10013. }
  10014. }
  10015. /**
  10016. * 切换横竖屏
  10017. *
  10018. */
  10019. setOrientation(orientation: number) {
  10020. this.windowClass.setPreferredOrientation(orientation).then(() => {
  10021. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  10022. }).catch((err: BusinessError) => {
  10023. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  10024. });
  10025. }
  10026. /**
  10027. * 画中画功能(悬浮歌词功能)
  10028. *
  10029. */
  10030. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  10031. pipController?: PiPWindow.PiPController;
  10032. navigationId: string = '';
  10033. @State curState: string = '';
  10034. @State curError: ResourceStr = '';
  10035. @State pipBg: string = '#E8E8E8'
  10036. @State buttonAction: string = '';
  10037. //开启画中画功能
  10038. async startPip() {
  10039. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  10040. if (!this.pipController) {
  10041. await this.createPipController();
  10042. }
  10043. if (!this.pipController) {
  10044. Logger.info(`[${TAG}] pipController create error`);
  10045. return;
  10046. }
  10047. await this.pipController.startPiP();
  10048. }
  10049. async stopPip() {
  10050. if (!this.pipController) {
  10051. Logger.info(`[${TAG}] pipController is not exist`);
  10052. return;
  10053. }
  10054. this.isOpenPip = false
  10055. await this.pipController.stopPiP();
  10056. }
  10057. async createPipController() {
  10058. this.pipController = await PiPWindow.create({
  10059. context: getContext(this),
  10060. componentController: this.xcomponentController,
  10061. navigationId: this.navigationId,
  10062. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  10063. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  10064. customUIController: this.nodeController,
  10065. });
  10066. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  10067. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  10068. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10069. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  10070. this.onStateChange(state, reason);
  10071. });
  10072. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  10073. this.onActionEvent(event, status);
  10074. });
  10075. }
  10076. destroyPipController() {
  10077. if (!this.pipController) {
  10078. return;
  10079. }
  10080. this.pipController.off('stateChange');
  10081. this.pipController.off('controlPanelActionEvent');
  10082. this.pipController = undefined;
  10083. }
  10084. onStateChange(state: PiPWindow.PiPState, reason: string) {
  10085. switch (state) {
  10086. case PiPWindow.PiPState.ABOUT_TO_START:
  10087. this.curState = 'ABOUT_TO_START';
  10088. this.curError = $r('app.string.current_error_hint');
  10089. break;
  10090. case PiPWindow.PiPState.STARTED:
  10091. this.curState = 'STARTED';
  10092. this.curError = $r('app.string.current_error_hint');
  10093. break;
  10094. case PiPWindow.PiPState.ABOUT_TO_STOP:
  10095. this.curState = 'ABOUT_TO_STOP';
  10096. this.curError = $r('app.string.current_error_hint');
  10097. break;
  10098. case PiPWindow.PiPState.STOPPED:
  10099. this.curState = 'STOPPED';
  10100. this.curError = $r('app.string.current_error_hint');
  10101. this.stopPip()
  10102. this.destroyPipController()
  10103. break;
  10104. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  10105. this.curState = 'ABOUT_TO_RESTORE';
  10106. this.curError = $r('app.string.current_error_hint');
  10107. break;
  10108. case PiPWindow.PiPState.ERROR:
  10109. this.curState = 'ERROR';
  10110. this.curError = reason;
  10111. break;
  10112. default:
  10113. break;
  10114. }
  10115. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  10116. }
  10117. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  10118. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  10119. switch (event) {
  10120. case 'playbackStateChanged':
  10121. if (status === 0) {
  10122. this.pause();
  10123. } else {
  10124. console.info('onecold startPlayOrResumePlay 9869')
  10125. this.startPlayOrResumePlay();
  10126. }
  10127. break;
  10128. case 'nextVideo':
  10129. // 切换到下一个视频
  10130. this.playNext()
  10131. break;
  10132. case 'previousVideo':
  10133. // 切换到上一个视频
  10134. this.playPrevious()
  10135. break;
  10136. case 'previousVideo':
  10137. // 切换到上一个视频
  10138. this.playPrevious()
  10139. break;
  10140. default:
  10141. }
  10142. this.buttonAction = event + `-status:${status}`;
  10143. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  10144. }
  10145. /**
  10146. * 画中画功能(悬浮歌词功能)结束
  10147. *
  10148. */
  10149. async doSearchCover(item: VideoItem): Promise<string> {
  10150. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  10151. this.isShowMoreView = false;
  10152. this.showTipsDialog();
  10153. return ''; // Return empty string when no API is configured
  10154. }
  10155. if (!item) {
  10156. return ''; // Return empty string if item is undefined
  10157. }
  10158. const artist = item?.artist || ''; // Use empty string if artist is missing
  10159. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  10160. }
  10161. /**
  10162. *api搜索封面
  10163. *item,根据title和artist
  10164. */
  10165. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  10166. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  10167. LogUtil.debug("onecold res =" + res);
  10168. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10169. if (item.filePath == this.currentSong?.filePath) {
  10170. this.cover = res;
  10171. if (this.currentSong) {
  10172. this.currentSong.pixelMapPath = res;
  10173. }
  10174. }
  10175. // Update pixel map path but always return res regardless of success
  10176. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  10177. if (success) {
  10178. this.doUpdateData();
  10179. console.log("onecold 更新音乐封面成功,数据库已同步");
  10180. } else {
  10181. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  10182. }
  10183. // Note: We don't resolve/reject here because we already returned res
  10184. });
  10185. LogUtil.debug("onecold this.cover =" + this.cover);
  10186. }
  10187. return res; // Always return res regardless of updatePixelMapPath result
  10188. });
  10189. }
  10190. @State jumpTopTime: number = 0
  10191. @State jumpEndTime: number = 0
  10192. @State isOpenJump: boolean = false
  10193. @Builder
  10194. JumpTopEndSheet() {
  10195. Scroll() {
  10196. Column() {
  10197. Column() {
  10198. Text('仅对本播放列表有效')
  10199. .fontSize(16)
  10200. .fontColor($r('app.color.text_color'))
  10201. // 跳过头尾
  10202. Column() {
  10203. Row() {
  10204. Text('跳过片头:')
  10205. .fontSize(16)
  10206. .fontColor($r('app.color.text_color'))
  10207. Text(this.jumpTopTime + 's')
  10208. .fontSize(16)
  10209. .fontColor($r('app.color.text_color'))
  10210. }
  10211. .margin({ bottom: 5 })
  10212. Row() {
  10213. Slider({
  10214. value: this.jumpTopTime,
  10215. min: 0,
  10216. max: 120,
  10217. step: 1,
  10218. style: SliderStyle.OutSet
  10219. })
  10220. .blockColor(this.themeColor)
  10221. .trackColor($r('app.color.speed_text_color'))
  10222. .selectedColor(Color.White)
  10223. .trackThickness(8)
  10224. .onChange((value: number) => {
  10225. this.jumpTopTime = value;
  10226. })
  10227. .width('85%')
  10228. }
  10229. .alignItems(VerticalAlign.Top)
  10230. }
  10231. .margin({ top: 10, bottom: 10 })
  10232. // 跳过头尾
  10233. Column() {
  10234. Row() {
  10235. Text('跳过片尾:')
  10236. .fontSize(16)
  10237. .fontColor($r('app.color.text_color'))
  10238. Text(this.jumpEndTime + 's')
  10239. .fontSize(16)
  10240. .fontColor($r('app.color.text_color'))
  10241. }
  10242. .margin({ bottom: 5 })
  10243. Row() {
  10244. Slider({
  10245. value: this.jumpEndTime,
  10246. min: 0,
  10247. max: 120,
  10248. step: 1,
  10249. style: SliderStyle.OutSet
  10250. })
  10251. .blockColor(this.themeColor)
  10252. .trackColor($r('app.color.speed_text_color'))
  10253. .selectedColor(Color.White)
  10254. .trackThickness(8)
  10255. .onChange((value: number) => {
  10256. this.jumpEndTime = value;
  10257. })
  10258. .width('85%')
  10259. }
  10260. .alignItems(VerticalAlign.Top)
  10261. }
  10262. .margin({ top: 10, bottom: 10 })
  10263. Row() {
  10264. Button('保存设置')
  10265. .fontColor(Color.White)
  10266. .layoutWeight(1)
  10267. .height(40)
  10268. .width(80)
  10269. .backgroundColor(this.themeColor)
  10270. .stateEffect(true)
  10271. .margin({ left: 0, bottom: 20 })
  10272. .onClick(async () => {
  10273. if (!Utility.isNoble()) {
  10274. this.isJumpSetting = false
  10275. this.isShowMoreView = false
  10276. this.showVipDialog()
  10277. return
  10278. }
  10279. if (this.currentSong === undefined) {
  10280. return
  10281. }
  10282. if (this.modeType === 0) {
  10283. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10284. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  10285. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  10286. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  10287. } else if (this.modeType === 1) { //媒体库
  10288. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  10289. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  10290. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  10291. } else if (this.modeType === 2) { //艺术家
  10292. if (this.currentSong?.artist) {
  10293. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  10294. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  10295. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  10296. }
  10297. } else if (this.modeType === 3) { //专辑
  10298. if (this.currentSong?.album) {
  10299. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  10300. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  10301. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  10302. }
  10303. }
  10304. ToastUtil.showShort("保存成功")
  10305. this.isJumpSetting = false
  10306. })
  10307. }
  10308. .margin({
  10309. left: 38,
  10310. right: 38,
  10311. top: 10,
  10312. bottom: 10
  10313. })
  10314. .width(120)
  10315. .height(50)
  10316. }
  10317. }
  10318. }
  10319. .width('100%')
  10320. .height('100%')
  10321. }
  10322. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  10323. private onStateVastChange(state: AVCastPickerState) {
  10324. if (state == AVCastPickerState.STATE_APPEARING) {
  10325. console.log('The picker starts showing.');
  10326. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10327. console.log('The picker finishes presenting.');
  10328. }
  10329. }
  10330. private showSelectLyric() {
  10331. DialogHelper.showActionSheetDialog({
  10332. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  10333. // sheets: ["本地歌词", "搜索歌词"],
  10334. sheets: [
  10335. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  10336. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  10337. ],
  10338. maskColor: Color.Transparent,
  10339. backgroundColor: $r('app.color.bg_card'),
  10340. transition: AnimationHelper.transitionInDown(666),
  10341. onAction: (index) => {
  10342. switch (index) {
  10343. case 0:
  10344. this.callFilePickerSelectFileForLyric()
  10345. break;
  10346. case 1:
  10347. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10348. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10349. this.initLyric(lyricPath);
  10350. }
  10351. break;
  10352. }
  10353. }
  10354. })
  10355. }
  10356. // 拉起picker选择文件管理器
  10357. async callFilePickerSelectFileForLyric(): Promise<void> {
  10358. try {
  10359. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  10360. DocumentSelectOptions.maxSelectNumber = 1
  10361. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  10362. let documentPicker = new picker.DocumentViewPicker();
  10363. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  10364. Logger.info(TAG,
  10365. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  10366. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  10367. this.saveVideoDatasLyric(DocumentSelectResult)
  10368. }
  10369. }).catch((err: BusinessError) => {
  10370. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  10371. });
  10372. } catch (err) {
  10373. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  10374. }
  10375. }
  10376. async saveVideoDatasLyric(uris: string[]) {
  10377. if (ArrayUtil.isEmpty(uris)) {
  10378. return
  10379. }
  10380. let newUris: string[] = [];
  10381. for (let i = 0; i < uris.length; i++) {
  10382. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  10383. Logger.info(TAG, 'filePath uri: ' + filePath);
  10384. newUris.push(filePath)
  10385. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  10386. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  10387. fileIo.copyFileSync(file.fd, file2.fd)
  10388. fileIo.closeSync(file);
  10389. fileIo.closeSync(file2);
  10390. this.initLyric(filePath,false,false,true)
  10391. }
  10392. }
  10393. private initDelayPlay(context: object) {
  10394. this.mContext = context;
  10395. }
  10396. startPipLyric() {
  10397. if (this.pipController) {
  10398. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10399. PiPWindow.PiPControlStatus.PLAY);
  10400. }
  10401. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  10402. if (this.isOpenPip) {
  10403. this.startPip()
  10404. } else {
  10405. this.stopPip()
  10406. }
  10407. }
  10408. //startOffset 从cue分轨时间开始播
  10409. private startPlayOrResumePlay(startOffset?:number) {
  10410. //针对dsf文件高采样率sampleRate>441000,统一转wav播放
  10411. const sampleRate = this.currentSong?.sampleRate||0
  10412. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  10413. console.info('onecold 采样率 ='+sampleRate)
  10414. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  10415. console.info('onecold newDsfPath ='+newDsfPath)
  10416. if(!FileUtil.accessSync(newDsfPath)){
  10417. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  10418. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  10419. this.videoUrl = newDsfPath
  10420. this.startPlay(startOffset)
  10421. }).catch((e:object)=>{
  10422. console.info("task1 catch e: " + e);
  10423. })
  10424. }else{
  10425. this.videoUrl = newDsfPath
  10426. this.startPlay(startOffset)
  10427. }
  10428. }else{
  10429. this.startPlay(startOffset)
  10430. }
  10431. }
  10432. startPlay(startOffset?:number) {
  10433. this.startPipLyric()
  10434. this.mDestroyPage = false;
  10435. this.animationState = AnimationStatus.Running
  10436. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  10437. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10438. this.stopProgressTask();
  10439. this.startProgressTask();
  10440. this.play(this.videoUrl.toString(),startOffset);
  10441. }
  10442. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  10443. this.mIjkMediaPlayer.start();
  10444. this.setProgress()
  10445. this.CONTROL_PlayStatus = PlayStatus.PLAY
  10446. }
  10447. this.setIsPlaying(true)
  10448. this.updateSessionPlayState(true)
  10449. this.watchStatus();
  10450. this.updateLastPlayTimeStr(this.videoUrl)
  10451. }
  10452. updateLastPlayTimeStr(filePath: string) {
  10453. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  10454. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10455. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  10456. return;
  10457. }
  10458. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  10459. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  10460. if (success) {
  10461. this.getHistoryList(false)
  10462. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  10463. } else {
  10464. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  10465. }
  10466. });
  10467. }
  10468. private completionNum(num: number): string | number {
  10469. if (num < 10) {
  10470. return '0' + num;
  10471. } else {
  10472. return num;
  10473. }
  10474. }
  10475. private stringForTime(timeMs: number): string {
  10476. let totalSeconds: number | string = (timeMs / 1000);
  10477. let newSeconds: number | string = totalSeconds % 60;
  10478. let minutes: number | string = (totalSeconds / 60) % 60;
  10479. let hours: number | string = totalSeconds / 3600;
  10480. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  10481. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  10482. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  10483. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  10484. if (this.isCurrentTime) {
  10485. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  10486. this.oldSeconds = newSeconds
  10487. } else {
  10488. newSeconds = this.oldSeconds
  10489. }
  10490. }
  10491. newSeconds = this.completionNum(newSeconds);
  10492. if (hours > 0) {
  10493. return hours + ":" + minutes + ":" + newSeconds;
  10494. } else {
  10495. return minutes + ":" + newSeconds;
  10496. }
  10497. }
  10498. private setProgress() {
  10499. let position = this.mIjkMediaPlayer.getCurrentPosition();
  10500. let duration = this.mIjkMediaPlayer.getDuration();
  10501. let pos = 0;
  10502. if (duration > 0) {
  10503. this.slideEnable = true;
  10504. let curPercent = position / duration;
  10505. pos = curPercent * 100;
  10506. if (pos > this.PROGRESS_MAX_VALUE) {
  10507. this.progressValue = this.PROGRESS_MAX_VALUE
  10508. } else {
  10509. this.progressValue = pos;
  10510. }
  10511. }
  10512. // LogUtils.getInstance()
  10513. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10514. this.totalTime = this.stringForTime(duration);
  10515. if (position > duration) {
  10516. position = duration;
  10517. }
  10518. this.isCurrentTime = true;
  10519. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  10520. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  10521. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  10522. this.currentTime = this.stringForTime(position);
  10523. this.isCurrentTime = false
  10524. if (this.mIjkMediaPlayer.isPlaying()) {
  10525. this.randomColor =
  10526. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  10527. //如果是开启AB循环
  10528. if(this.isOpenAB){
  10529. if(position >=this.jumpBTime){
  10530. this.seekTo(this.jumpATime+'')
  10531. return
  10532. }
  10533. }
  10534. // 判断是否播放到结束时间
  10535. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  10536. if (position >= duration - this.jumpEndTime * 1000) {
  10537. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  10538. this.CONTROL_PlayStatus = PlayStatus.INIT
  10539. this.startPlayOrResumePlay();
  10540. }else if (this.playType == 2) { //2:正常播放,单曲播完
  10541. this.showRePlay();
  10542. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  10543. this.progressValue = this.PROGRESS_MAX_VALUE;
  10544. this.slideEnable = false;
  10545. this.stop();
  10546. // ToastUtil.showToast('开始重新播放')
  10547. }else{
  10548. this.playNext()
  10549. }
  10550. }
  10551. }
  10552. } else {
  10553. this.randomColor = 'rbg(0,0,0)'
  10554. }
  10555. }
  10556. private startProgressTask() {
  10557. let that = this;
  10558. this.updateProgressTimer = setInterval(() => {
  10559. //LogUtils.getInstance().LOGI("startProgressTask");
  10560. if (!that.mDestroyPage) {
  10561. that.setProgress();
  10562. }
  10563. }, 300);
  10564. }
  10565. private stopProgressTask() {
  10566. LogUtils.getInstance().LOGI("stopProgressTask");
  10567. clearInterval(this.updateProgressTimer);
  10568. }
  10569. private showLoadIng() {
  10570. this.loadingVisible = Visibility.Visible;
  10571. this.replayVisible = Visibility.None;
  10572. }
  10573. private hideLoadIng() {
  10574. this.loadingVisible = Visibility.None;
  10575. this.replayVisible = Visibility.None;
  10576. }
  10577. private showRePlay() {
  10578. this.loadingVisible = Visibility.None;
  10579. this.replayVisible = Visibility.Visible;
  10580. }
  10581. private async play(url: string,startOffset?:number) {
  10582. let that = this;
  10583. that.showLoadIng();
  10584. this.isOpenAB = false
  10585. //设置XComponent回调的context
  10586. if (!!this.mContext) {
  10587. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  10588. }
  10589. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10590. this.mIjkMediaPlayer.reset();
  10591. }
  10592. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  10593. //设置debug模式
  10594. this.mIjkMediaPlayer.setDebug(false);
  10595. //初始化配置
  10596. this.mIjkMediaPlayer.native_setup();
  10597. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  10598. if(this.volumeSmall){
  10599. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  10600. this.mIjkMediaPlayer.setVolume('1', '1');
  10601. }else{
  10602. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10603. }
  10604. }else{
  10605. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10606. }
  10607. //设置视频源
  10608. this.mIjkMediaPlayer.setDataSource(url);
  10609. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  10610. const headers = new Map<string, string>();
  10611. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  10612. headers.set("Accept", "*/*");
  10613. headers.set("Range", "bytes=0-");
  10614. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  10615. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  10616. //如果封面为空,则搜索封面
  10617. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  10618. }
  10619. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  10620. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10621. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  10622. if (this.currentSong.webdav_account_id) {
  10623. try {
  10624. const webdavManager = WebdavManager.getInstance();
  10625. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  10626. if (webDavHeaders && webDavHeaders.size > 0) {
  10627. webDavHeaders.forEach((value, key) => headers.set(key, value));
  10628. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  10629. } else {
  10630. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  10631. }
  10632. } catch (error) {
  10633. const err = error as Error;
  10634. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  10635. }
  10636. } else {
  10637. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  10638. }
  10639. }
  10640. // 统一设置带认证的请求头
  10641. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  10642. if (this.currentSong&&this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10643. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  10644. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  10645. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  10646. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  10647. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  10648. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  10649. // 缓冲和播放优化设置
  10650. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  10651. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  10652. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  10653. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  10654. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  10655. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  10656. // 网络相关设置
  10657. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  10658. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  10659. // 重连设置
  10660. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  10661. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  10662. }
  10663. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  10664. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  10665. // }
  10666. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10667. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  10668. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  10669. const fileSize = await this.getFileSize(this.videoUrl);
  10670. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  10671. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  10672. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  10673. }
  10674. // 使用软件解码(通常比硬件解码更节省内存)
  10675. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  10676. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  10677. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  10678. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  10679. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  10680. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  10681. //停止预读的最小帧数
  10682. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  10683. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  10684. // 设置其他缓冲相关选项
  10685. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  10686. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  10687. //启动预加载
  10688. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  10689. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  10690. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  10691. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  10692. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  10693. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  10694. // 因此需要播放器丢包,才不会累积延时
  10695. // 这个和第三个参数packet-buffering无关。
  10696. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  10697. // 无限制收流
  10698. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  10699. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  10700. // 屏幕常亮
  10701. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  10702. // 设置超时
  10703. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  10704. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  10705. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  10706. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  10707. // 变速播放
  10708. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  10709. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10710. let Speed = this.mIjkMediaPlayer.getSpeed()
  10711. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  10712. //是否开启循环播放
  10713. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  10714. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  10715. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  10716. if (height === 0) {
  10717. return;
  10718. }
  10719. const va = width / height;
  10720. const vpa = that.videoParentAspectRatio;
  10721. if (vpa > va) {
  10722. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  10723. } else {
  10724. that.videoWidth = '100%';
  10725. }
  10726. if (width && height) {
  10727. that.videoAspectRatio = width / height;
  10728. }
  10729. LogUtils.getInstance()
  10730. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  10731. that.hideLoadIng();
  10732. }
  10733. }
  10734. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  10735. let mOnPreparedListener: OnPreparedListener = {
  10736. onPrepared: async () => {
  10737. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  10738. try {
  10739. // this.cover = this.songList[this.curIndex].pixelMapPath
  10740. // this.artist = this.songList[this.curIndex].artist
  10741. // this.videoUrl = this.songList[this.curIndex].filePath
  10742. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10743. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  10744. this.setImageColor2(this.cover)
  10745. } else {
  10746. this.getImageColor();
  10747. }
  10748. //保存碰一碰分享的当前的歌曲
  10749. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  10750. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10751. await this.initLyric(lyricPath);
  10752. setTimeout(() => {
  10753. this.avSessionController.initAvSession(false);
  10754. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  10755. this.setAvSessionListener();
  10756. this.updateSessionPlayState(true)
  10757. this.setCurrentPlayMode()
  10758. }, 500)
  10759. if(startOffset&&startOffset>0){//cue分轨播放
  10760. this.seekTo(startOffset + "");
  10761. this.saveLastPlayList()
  10762. return
  10763. }
  10764. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10765. let timeoutPlay = 0
  10766. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10767. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  10768. timeoutPlay = 1000
  10769. }
  10770. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  10771. if (this.modeType === 0) { //文件夹
  10772. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10773. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  10774. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  10775. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  10776. } else if (this.modeType === 1) { //媒体库
  10777. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  10778. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  10779. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  10780. } else if (this.modeType === 2) { //艺术家
  10781. if (this.currentSong?.artist) {
  10782. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  10783. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  10784. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  10785. }
  10786. } else if (this.modeType === 3) { //专辑
  10787. if (this.currentSong?.album) {
  10788. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  10789. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  10790. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  10791. }
  10792. }
  10793. this.duration = this.mIjkMediaPlayer.getDuration()
  10794. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  10795. if (this.mIjkMediaPlayer != null) {
  10796. let jumpTopTimeMs = this.jumpTopTime*1000;
  10797. if (jumpTopTimeMs <= this.duration) {
  10798. // 调用 seekTo 方法,跳到指定时间
  10799. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  10800. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  10801. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10802. console.log('onecold position = '+position);
  10803. if (position > jumpTopTimeMs) {
  10804. jumpTopTimeMs = position
  10805. }
  10806. }
  10807. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10808. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10809. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  10810. }
  10811. }, timeoutPlay)
  10812. } else {
  10813. // 提示用户无法跳过
  10814. ToastUtil.showToast('跳过时间超过视频时长');
  10815. }
  10816. }
  10817. } else {
  10818. this.jumpTopTime = 0
  10819. this.jumpEndTime = 0
  10820. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  10821. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  10822. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  10823. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  10824. //记忆播放(每一首都会记忆播放)
  10825. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10826. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10827. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  10828. this.restorePlaybackPosition() //读取播放记忆功能
  10829. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  10830. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  10831. this.restorePlaybackPosition() //读取播放记忆功能
  10832. }
  10833. this.isFirstStartPlay = false
  10834. }, timeoutPlay)
  10835. } else {
  10836. this.isFirstStartPlay = false
  10837. }
  10838. }
  10839. this.saveLastPlayList()
  10840. } catch (error) {
  10841. let err: BusinessError = error as BusinessError;
  10842. console.error('onecold failed with err: ' + JSON.stringify(err));
  10843. }
  10844. }
  10845. }
  10846. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  10847. let mOnTimedTextListener: OnTimedTextListener = {
  10848. onTimedText: () => {
  10849. }
  10850. }
  10851. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  10852. let mOnCompletionListener: OnCompletionListener = {
  10853. onCompletion: () => {
  10854. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  10855. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  10856. this.playNext()
  10857. } else if (this.playType == 1) { //1:单片重复播放
  10858. this.CONTROL_PlayStatus = PlayStatus.INIT
  10859. console.info('onecold startPlayOrResumePlay 10592')
  10860. that.startPlayOrResumePlay();
  10861. } else if (this.playType == 2) { //2:正常播放,单曲播完
  10862. that.showRePlay();
  10863. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  10864. that.progressValue = this.PROGRESS_MAX_VALUE;
  10865. that.slideEnable = false;
  10866. that.stop();
  10867. // ToastUtil.showToast('开始重新播放')
  10868. } else if (this.playType == 3) { //3:随机播放
  10869. this.randomPlay()
  10870. }
  10871. }
  10872. }
  10873. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  10874. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  10875. onBufferingUpdate: (percent: number) => {
  10876. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  10877. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  10878. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  10879. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  10880. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  10881. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  10882. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  10883. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  10884. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  10885. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  10886. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  10887. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  10888. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  10889. let Looping = this.mIjkMediaPlayer.isLooping()
  10890. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  10891. }
  10892. }
  10893. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  10894. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  10895. onSeekComplete: () => {
  10896. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  10897. console.info('onecold startPlayOrResumePlay 10643')
  10898. that.startPlayOrResumePlay();
  10899. }
  10900. }
  10901. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  10902. let mOnInfoListener: OnInfoListener = {
  10903. onInfo: (what: number, extra: number) => {
  10904. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  10905. that.hideLoadIng();
  10906. }
  10907. }
  10908. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  10909. let mOnErrorListener: OnErrorListener = {
  10910. onError: (what: number, extra: number) => {
  10911. this.stopProgressTask();
  10912. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  10913. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  10914. // 检查是否为WebDAV播放错误
  10915. let isWebDavError = false;
  10916. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV && this.currentSong.filePath) {
  10917. try {
  10918. const globalContext = GlobalContext.getContext();
  10919. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  10920. if (webDavAuthInfo) {
  10921. isWebDavError = true;
  10922. }
  10923. } catch (error) {
  10924. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  10925. }
  10926. }
  10927. if (isWebDavError) {
  10928. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  10929. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  10930. // this.currentWebDavAuthInfo = null;
  10931. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  10932. // 根据错误代码提供更具体的错误信息
  10933. let errorMessage = "WebDAV播放失败";
  10934. if (what === -1) { // 网络错误
  10935. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  10936. } else if (what === -1004) { // HTTP 404
  10937. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  10938. } else if (what === -1001) { // 超时
  10939. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  10940. } else if (what === -1003) { // 无法解析主机
  10941. errorMessage = "无法连接到WebDAV服务器";
  10942. }
  10943. ToastUtil.showToast(errorMessage);
  10944. } else {
  10945. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10946. !this.videoUrl.startsWith('http://') &&
  10947. !this.videoUrl.startsWith('https://') &&
  10948. !FileUtil.accessSync(this.videoUrl)) {
  10949. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  10950. } else {
  10951. ToastUtil.showToast(getContext()
  10952. .resourceManager
  10953. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  10954. }
  10955. }
  10956. that.hideLoadIng();
  10957. }
  10958. }
  10959. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  10960. this.mIjkMediaPlayer.setMessageListener();
  10961. this.mIjkMediaPlayer.prepareAsync();
  10962. this.mIjkMediaPlayer.start();
  10963. }
  10964. //保存最后播放的那首歌和已经对应的播放列表
  10965. saveLastPlayList() {
  10966. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  10967. PreferencesUtil.putSync('LastMusicList', this.songList)
  10968. }
  10969. // 清空播放记录
  10970. clearVideoHistory() {
  10971. this.table.clearPlayHistory((success: boolean, error?: string) => {
  10972. if (success) {
  10973. this.historyList = [];
  10974. this.updateListData(this.historyList)
  10975. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  10976. ToastUtil.showToast('清空播放记录成功')
  10977. } else {
  10978. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  10979. }
  10980. });
  10981. }
  10982. public async setAvSessionListener() {
  10983. if (!this.avSessionController) {
  10984. return;
  10985. }
  10986. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  10987. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  10988. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  10989. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  10990. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  10991. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  10992. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  10993. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  10994. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  10995. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  10996. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  10997. }
  10998. setLoopMode() {
  10999. let itype = this.playType + 1
  11000. if (itype >= 4) {
  11001. this.playType = 0
  11002. ToastUtil.showToast('连续播放')
  11003. } else if (itype === 1) {
  11004. this.playType = 1
  11005. ToastUtil.showToast('单曲循环')
  11006. } else if (itype === 2) {
  11007. this.playType = 2
  11008. ToastUtil.showToast('单曲播完')
  11009. } else if (itype === 3) {
  11010. this.playType = 3
  11011. ToastUtil.showToast('随机播放')
  11012. } else if (itype === 0) {
  11013. this.playType = 0
  11014. ToastUtil.showToast('连续播放')
  11015. }
  11016. PreferencesUtil.putSync('musicPlayType', this.playType)
  11017. this.setCurrentPlayMode()
  11018. }
  11019. private sessionSetLoopModeCallback = (mode: number) => {
  11020. if (this.mIjkMediaPlayer != null) {
  11021. ToastUtil.showToast('当前播放模式:' + mode)
  11022. Logger.info('onecold 当前播放模式= ' + mode)
  11023. let hmPlayMode = mode + 1
  11024. if (hmPlayMode >= 4) {
  11025. hmPlayMode = 0
  11026. }
  11027. if (hmPlayMode === 1) {
  11028. this.playType = 1
  11029. ToastUtil.showToast('单曲循环')
  11030. } else if (hmPlayMode === 0) {
  11031. this.playType = 2
  11032. ToastUtil.showToast('单曲播完')
  11033. } else if (hmPlayMode === 3) {
  11034. this.playType = 3
  11035. ToastUtil.showToast('随机播放')
  11036. } else if (hmPlayMode === 2) {
  11037. this.playType = 0
  11038. ToastUtil.showToast('连续播放')
  11039. }
  11040. PreferencesUtil.putSync('musicPlayType', this.playType)
  11041. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  11042. let playBackState: avSession.AVPlaybackState = {
  11043. loopMode: hmPlayMode,
  11044. };
  11045. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  11046. console.info(`set setLoopMode AVPlaybackState successfully`);
  11047. }).catch((err: BusinessError) => {
  11048. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11049. });
  11050. }
  11051. }
  11052. setCurrentPlayMode() {
  11053. if (!this.avSessionController) {
  11054. return;
  11055. }
  11056. let mLoopMode = 0
  11057. switch (this.playType) {
  11058. case 0:
  11059. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  11060. break;
  11061. case 1:
  11062. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  11063. break;
  11064. case 2:
  11065. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  11066. break;
  11067. case 3:
  11068. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  11069. break;
  11070. }
  11071. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  11072. let playBState: avSession.AVPlaybackState = {
  11073. loopMode: mLoopMode,
  11074. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  11075. };
  11076. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  11077. console.info(`set setLoopMode AVPlaybackState successfully`);
  11078. }).catch((err: BusinessError) => {
  11079. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11080. });
  11081. }
  11082. private sessionToggleFavoriteCallback = (assetId: string) => {
  11083. if (this.mIjkMediaPlayer != null && this.currentSong) {
  11084. console.info(`on toggleFavorite `);
  11085. // 应用收到收藏命令,进行收藏处理。
  11086. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  11087. this.doFav(this.currentSong)
  11088. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  11089. let playbackState: avSession.AVPlaybackState = {
  11090. isFavorite: !this.isFac,
  11091. };
  11092. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  11093. console.info(`SetAVPlaybackState successfully`);
  11094. }).catch((err: BusinessError) => {
  11095. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  11096. });
  11097. }
  11098. }
  11099. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  11100. device: avSession.OutputDeviceInfo) => {
  11101. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  11102. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11103. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  11104. await this.startCasting();
  11105. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11106. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  11107. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  11108. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  11109. if (device) {
  11110. this.endCasting();
  11111. }
  11112. }
  11113. };
  11114. private async startCasting() {
  11115. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11116. this.setPlaybackStateChangeListener();
  11117. this.pause();
  11118. this.initQueueItem();
  11119. this.prepare();
  11120. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11121. refToIsCasting?.set(true);
  11122. this.castSeek = true;
  11123. this.isCastPlaying = true;
  11124. }
  11125. async changeCasting() {
  11126. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11127. this.initQueueItem();
  11128. this.prepare();
  11129. this.setPlaybackStateChangeListener();
  11130. this.isCastPlaying = true;
  11131. this.castSeek = true;
  11132. }
  11133. public endCasting() {
  11134. this.avSessionController.getAvSession()?.stopCasting();
  11135. this.stopCast();
  11136. this.isCastPlaying = false;
  11137. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11138. refToIsCasting?.set(false);
  11139. this.pause();
  11140. this.setIsPlaying(false);
  11141. // if (this.curIndex === this.curSource.index) {
  11142. // this.play
  11143. // this.seek(this.currentTime * 1000);
  11144. // this.setIsPlaying(true);
  11145. // } else {
  11146. // this.pauseVideo();
  11147. // this.setIsPlaying(false);
  11148. // }
  11149. }
  11150. public setIsPlaying(isPlayer: boolean) {
  11151. this.isPlaying = isPlayer;
  11152. // 发送播放状态变化事件给歌单详情页面
  11153. try {
  11154. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  11155. const currentFilePath = this.currentSong?.filePath || ''
  11156. const eventData: emitter.EventData = {
  11157. data: {
  11158. isPlaying: this.isPlaying,
  11159. curIndex: this.curIndex,
  11160. currentFilePath: currentFilePath
  11161. }
  11162. };
  11163. emitter.emit(eventPlaybackStatus, eventData)
  11164. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  11165. } catch (error) {
  11166. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  11167. }
  11168. }
  11169. private setPlaybackStateChangeListener(): void {
  11170. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  11171. this.castController?.on('endOfStream', this.reloadCasting);
  11172. this.castController?.on('playNext', this.playNextCallback);
  11173. this.castController?.on('playPrevious', this.playPreviousCallback);
  11174. }
  11175. private updateSessionPlayState(isPlay: boolean): void {
  11176. // if(!this.isBgPlayOpen)
  11177. // return
  11178. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  11179. this.setAVSessionPlayState({
  11180. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  11181. position: {
  11182. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  11183. updateTime: new Date().getTime()
  11184. }
  11185. });
  11186. }
  11187. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  11188. this.avSessionController.setAvSessionPlayState(playbackState)
  11189. }
  11190. private positionChange(position: number) {
  11191. this.currentTime2 = position / 1000;
  11192. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  11193. }
  11194. private playDurationChange(duration: number) {
  11195. this.duration = duration;
  11196. this.durationTime = Math.floor(this.duration / 1000);
  11197. this.durationStringTime = secondToTime((this.durationTime));
  11198. }
  11199. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  11200. const duration = playbackState?.extras?.duration;
  11201. if (typeof duration === 'number') {
  11202. this.playDurationChange(duration as number);
  11203. }
  11204. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  11205. this.positionChange(playbackState?.position?.elapsedTime);
  11206. }
  11207. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  11208. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  11209. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  11210. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  11211. this.isCastPlaying = false;
  11212. }
  11213. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  11214. this.isCastPlaying = true;
  11215. }
  11216. };
  11217. private reloadCasting = async () => {
  11218. let item = this.songList[this.curIndex];
  11219. let uri = fileUri.getUriFromPath(item.filePath);
  11220. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11221. // description.startPosition = 0;
  11222. this.castItem = {
  11223. itemId: this.curIndex,
  11224. description: {
  11225. assetId: item.filePath,
  11226. title: item.name,
  11227. artist: '',
  11228. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11229. // mediaUri: item.filePath,
  11230. fdSrc: {
  11231. fd: file.fd
  11232. },
  11233. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11234. mediaType: 'VIDEO',
  11235. mediaSize: item.videoSize,
  11236. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11237. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11238. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11239. duration: this.duration,
  11240. // albumCoverUri: 'https://www.example.jpeg',
  11241. // albumTitle: '《ExampleAlbum》',
  11242. appName: this.appName,
  11243. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11244. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11245. }
  11246. };
  11247. this.prepare();
  11248. this.isCastPlaying = true;
  11249. };
  11250. public playNextCallback = (): void => {
  11251. this.playNext()
  11252. };
  11253. public playPreviousCallback = (): void => {
  11254. this.playPrevious()
  11255. };
  11256. async prepare() {
  11257. await this.castController?.prepare(this.castItem);
  11258. await this.castController?.start(this.castItem);
  11259. }
  11260. public initQueueItem() {
  11261. let item = this.songList[this.curIndex];
  11262. let time = this.currentTime;
  11263. let uri = fileUri.getUriFromPath(item.filePath);
  11264. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11265. this.castItem = {
  11266. itemId: this.curIndex,
  11267. description: {
  11268. assetId: item.filePath,
  11269. title: item.name,
  11270. artist: '',
  11271. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11272. fdSrc: {
  11273. fd: file.fd
  11274. },
  11275. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11276. mediaType: 'AUDIO',
  11277. mediaSize: item.videoSize,
  11278. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11279. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11280. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11281. duration: this.duration,
  11282. // albumCoverUri: 'https://www.example.jpeg',
  11283. // albumTitle: '《ExampleAlbum》',
  11284. appName: this.appName,
  11285. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11286. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11287. }
  11288. };
  11289. }
  11290. async stopCast() {
  11291. try {
  11292. this.castController?.off('playbackStateChange');
  11293. this.castController?.off('endOfStream');
  11294. this.castController?.off('playNext');
  11295. this.castController?.off('playPrevious');
  11296. this.castController?.off('error');
  11297. } catch (error) {
  11298. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  11299. }
  11300. }
  11301. private sessionPlayCallback = (): void => {
  11302. console.info('onecold playOrPause 11050')
  11303. this.playOrPause()
  11304. };
  11305. private sessionPauseCallback = (): void => {
  11306. console.info('onecold playOrPause 11054')
  11307. this.pause()
  11308. };
  11309. private playOrPause() {
  11310. if (!this.debounce()) {
  11311. return;
  11312. }
  11313. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11314. this.pause();
  11315. } else {
  11316. console.info('onecold startPlayOrResumePlay 11064')
  11317. this.startPlayOrResumePlay();
  11318. this.playChange()
  11319. }
  11320. }
  11321. private sessionPlayNextCallback = (): void => {
  11322. this.playNext()
  11323. };
  11324. private sessionPlayPreviousCallback = (): void => {
  11325. this.playPrevious()
  11326. };
  11327. private sessionStopCallback = (): void => {
  11328. this.stop()
  11329. };
  11330. private sessionFastForwardCallback = (time?: number) => {
  11331. if (!time) {
  11332. return;
  11333. }
  11334. if (this.mIjkMediaPlayer != null) {
  11335. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11336. let seeTime = curPosition + time * 1000;
  11337. // 限制 seekValue 在合法范围内
  11338. if (seeTime < 0) {
  11339. seeTime = 0;
  11340. } else if (seeTime > this.duration) {
  11341. seeTime = this.duration;
  11342. }
  11343. Logger.info('onecold seeTime= ' + seeTime)
  11344. this.setSeekToActionProgress(seeTime)
  11345. this.seekTo(seeTime + "")
  11346. }
  11347. };
  11348. /**
  11349. * Gesture method onActionUpdate.
  11350. *
  11351. * @param event Gesture event.手势拖动设置快进和后退
  11352. */
  11353. private setSeekToActionProgress(position: number) {
  11354. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  11355. let duration = this.mIjkMediaPlayer.getDuration();
  11356. let pos = 0;
  11357. if (duration > 0) {
  11358. this.slideEnable = true;
  11359. let curPercent = position / duration;
  11360. pos = curPercent * 100;
  11361. if (pos > this.PROGRESS_MAX_VALUE) {
  11362. this.progressValue = this.PROGRESS_MAX_VALUE
  11363. } else {
  11364. this.progressValue = pos;
  11365. }
  11366. }
  11367. // LogUtils.getInstance()
  11368. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11369. this.totalTime = this.stringForTime(duration);
  11370. if (position > duration) {
  11371. position = duration;
  11372. }
  11373. this.isCurrentTime = true;
  11374. this.currentTime = this.stringForTime(position);
  11375. this.isCurrentTime = false
  11376. }
  11377. private sessionRewindCallback = (time?: number) => {
  11378. if (!time) {
  11379. return;
  11380. }
  11381. if (this.mIjkMediaPlayer != null) {
  11382. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11383. let seeTime = curPosition - time * 1000;
  11384. // 限制 seekValue 在合法范围内
  11385. if (seeTime < 0) {
  11386. seeTime = 0;
  11387. } else if (seeTime > this.duration) {
  11388. seeTime = this.duration;
  11389. }
  11390. Logger.info('onecold seeTime= ' + seeTime)
  11391. this.setSeekToActionProgress(seeTime)
  11392. this.seekTo(seeTime + "")
  11393. }
  11394. };
  11395. private sessionSeekCallback = (seekTime: number) => {
  11396. if (this.mIjkMediaPlayer != null) {
  11397. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11398. this.seekTo(seekTime + "")
  11399. }
  11400. };
  11401. private async getFileSize(filePath: string): Promise<number> {
  11402. try {
  11403. const stat = await fs.stat(filePath);
  11404. return stat.size;
  11405. } catch (err) {
  11406. console.error('Failed to get file size: ' + err.message);
  11407. return 0;
  11408. }
  11409. }
  11410. private pause() {
  11411. if (this.mIjkMediaPlayer.isPlaying()) {
  11412. this.savePlaybackPosition();
  11413. this.mIjkMediaPlayer.pause();
  11414. this.setProgress();
  11415. this.mDestroyPage = true;
  11416. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  11417. this.updateSessionPlayState(false)
  11418. this.playChange()
  11419. if (this.pipController) {
  11420. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11421. PiPWindow.PiPControlStatus.PAUSE);
  11422. }
  11423. }
  11424. }
  11425. private stop() {
  11426. this.savePlaybackPosition();
  11427. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11428. this.mIjkMediaPlayer.stop();
  11429. this.mIjkMediaPlayer.release();
  11430. this.stopProgressTask();
  11431. this.updateSessionPlayState(false)
  11432. this.playChange()
  11433. this.watchStatus();
  11434. }
  11435. //保持记忆播放功能
  11436. private savePlaybackPosition() {
  11437. if (this.mIjkMediaPlayer != null) {
  11438. const position = this.mIjkMediaPlayer.getCurrentPosition();
  11439. // ToastUtil.showToast('保存记忆播放 = ' + position)
  11440. const duration = this.mIjkMediaPlayer.getDuration();
  11441. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  11442. // 如果播放位置接近视频末尾,则保存 position 为 0
  11443. const playbackPosition = (duration - position < threshold) ? 0 : position;
  11444. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  11445. }
  11446. }
  11447. //获取记忆播放功能
  11448. private restorePlaybackPosition() {
  11449. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11450. // ToastUtil.showToast('position = ' + position)
  11451. if (this.mIjkMediaPlayer != null && position > 0) {
  11452. // ToastUtil.showToast('seekTo = ' + position)
  11453. this.seekTo(position + "");
  11454. }
  11455. }
  11456. private seekTo(value: string) {
  11457. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  11458. ToastUtil.showToast('wma格式不支持拖动快进。')
  11459. return
  11460. }
  11461. this.isSeekTo = true
  11462. this.mIjkMediaPlayer.seekTo(value);
  11463. console.info('onecold startPlayOrResumePlay 11227')
  11464. // this.startPlayOrResumePlay()
  11465. // 在这里恢复计时器状态
  11466. this.setProgress()
  11467. this.isSeekTo = false
  11468. }
  11469. // 添加到下一首播放
  11470. private addToNextPlay(song: VideoItem) {
  11471. if (!this.debounce()) {
  11472. return;
  11473. }
  11474. if (this.currentSong) {
  11475. if (this.currentSong === song) {
  11476. ToastUtil.showToast('当前已经在播放这首歌了!')
  11477. return
  11478. }
  11479. }
  11480. // 如果未开始播放或队列为空
  11481. if (this.curIndex === -1 || this.songList.length === 0) {
  11482. this.songList = [song];
  11483. this.curIndex = 0;
  11484. this.doPlay(song)
  11485. return;
  11486. }
  11487. // 插入到当前索引+1的位置
  11488. const insertPos = this.curIndex + 1;
  11489. this.songList.splice(insertPos, 0, song);
  11490. this.songList = [...this.songList]; // 触发状态更新
  11491. this.sonDataSource.pushArrayData(this.songList)
  11492. ToastUtil.showToast('已添加至下一首播放')
  11493. }
  11494. //后退10s,可再设置设置默认几秒
  11495. backForward() {
  11496. if(this.mIjkMediaPlayer){
  11497. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11498. let value = pos - Number(this.fastForwardSeconds) * 1000;
  11499. this.seekTo(value+"");
  11500. }
  11501. }
  11502. //快进10s,可再设置设置默认几秒
  11503. fastForward() {
  11504. if(this.mIjkMediaPlayer){
  11505. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11506. let value = pos + Number(this.fastForwardSeconds) * 1000;
  11507. this.seekTo(value+"");
  11508. }
  11509. }
  11510. //下一个
  11511. private playNext() {
  11512. if (!this.debounce()) {
  11513. return;
  11514. }
  11515. if (this.playType == 3) { //3:随机播放
  11516. this.randomPlay()
  11517. return;
  11518. }
  11519. if (ArrayUtil.isNotEmpty(this.songList)) {
  11520. if (this.curIndex == this.songList.length - 1) {
  11521. this.curIndex = 0;
  11522. } else {
  11523. this.curIndex++;
  11524. }
  11525. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11526. this.stop();
  11527. this.currentSong = this.songList[this.curIndex]
  11528. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  11529. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  11530. }else{
  11531. this.videoUrl = this.currentSong.filePath
  11532. }
  11533. this.artist = this.songList[this.curIndex].artist
  11534. this.name = this.songList[this.curIndex].name
  11535. //this.cover = this.songList[this.curIndex].pixelMapPath
  11536. this.changeImageAnimation()
  11537. }
  11538. }
  11539. changeImageAnimation() {
  11540. if(this.openSkipSongAnimate){
  11541. // 第一步:淡出动画
  11542. this.getUIContext()?.animateTo({
  11543. duration: 500,
  11544. curve: Curve.EaseOut,
  11545. }, () => {
  11546. this.opacityValueImage = 0.1;
  11547. if(this.isCoverRectangle){
  11548. this.scaleValueImage = 0.88
  11549. }
  11550. });
  11551. // 第二步:切换图片后淡入
  11552. setTimeout(() => {
  11553. this.cover = this.songList[this.curIndex].pixelMapPath
  11554. this.getUIContext()?.animateTo({
  11555. duration: 500,
  11556. curve: Curve.EaseIn,
  11557. }, () => {
  11558. this.opacityValueImage = 1;
  11559. this.scaleValueImage = 1 // 图标恢复到原始大小
  11560. this.startPlayOrResumePlay()
  11561. });
  11562. }, 500);
  11563. }else{
  11564. this.cover = this.songList[this.curIndex].pixelMapPath
  11565. this.startPlayOrResumePlay()
  11566. }
  11567. }
  11568. // 存储已播放的歌曲索引
  11569. private playedIndices: Set<number> = new Set();
  11570. //随机播放
  11571. private randomPlay() {
  11572. // if (!this.debounce()) {
  11573. // return;
  11574. // }
  11575. if (ArrayUtil.isNotEmpty(this.songList)) {
  11576. if (this.songList.length > 3) {
  11577. // 如果所有歌曲都播放过一次,清空已播放索引集合
  11578. if (this.playedIndices.size === this.songList.length) {
  11579. this.playedIndices.clear();
  11580. }
  11581. // 随机选择一个未播放的歌曲索引
  11582. let newIndex: number;
  11583. // 添加超时机制防止无限循环
  11584. let attempt = 0;
  11585. const maxAttempts = 100; // 根据需求调整
  11586. do {
  11587. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  11588. attempt++;
  11589. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  11590. if (attempt >= maxAttempts) {
  11591. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  11592. newIndex = Math.floor(Math.random() * this.songList.length);
  11593. }
  11594. this.curIndex = newIndex;
  11595. this.playedIndices.add(newIndex);
  11596. } else {
  11597. // 当歌曲数量小于或等于3时,直接播放下一首
  11598. if (this.curIndex == this.songList.length - 1) {
  11599. this.curIndex = 0;
  11600. } else {
  11601. this.curIndex++;
  11602. }
  11603. }
  11604. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11605. this.stop();
  11606. this.currentSong = this.songList[this.curIndex];
  11607. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  11608. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  11609. }else{
  11610. this.videoUrl = this.currentSong.filePath
  11611. }
  11612. this.name = this.songList[this.curIndex].name;
  11613. this.artist = this.songList[this.curIndex].artist
  11614. // this.cover = this.songList[this.curIndex].pixelMapPath
  11615. this.changeImageAnimation()
  11616. }
  11617. }
  11618. private playIndex(index: number) {
  11619. if (!this.debounce()) {
  11620. return;
  11621. }
  11622. if (ArrayUtil.isNotEmpty(this.songList)) {
  11623. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11624. this.stop();
  11625. this.currentSong = this.songList[this.curIndex]
  11626. if(this.currentSong.type===CommonConstants.TYPE_WEBDAV){
  11627. this.videoUrl = this.songList[index].filePath.replace(/ /g, '%20');
  11628. }else{
  11629. this.videoUrl = this.songList[index].filePath
  11630. }
  11631. this.name = this.songList[index].name
  11632. this.artist = this.songList[this.curIndex].artist
  11633. this.curIndex = index;
  11634. this.changeImageAnimation()
  11635. }
  11636. }
  11637. //上一个
  11638. private playPrevious() {
  11639. if (!this.debounce()) {
  11640. return;
  11641. }
  11642. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  11643. this.randomModePlayFromHistory()
  11644. return;
  11645. }
  11646. if (this.curIndex == 0) {
  11647. this.curIndex = this.songList.length - 1;
  11648. } else {
  11649. this.curIndex--;
  11650. }
  11651. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11652. this.stop();
  11653. this.currentSong = this.songList[this.curIndex]
  11654. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  11655. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11656. }else{
  11657. this.videoUrl = this.songList[this.curIndex].filePath
  11658. }
  11659. this.name = this.songList[this.curIndex].name
  11660. this.artist = this.songList[this.curIndex].artist
  11661. this.changeImageAnimation()
  11662. }
  11663. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  11664. private randomModePlayFromHistory() {
  11665. if (this.historyList.length >= 2) {
  11666. // 播放历史记录的第二首
  11667. const prevSong = this.historyList[1];
  11668. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  11669. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11670. this.stop();
  11671. this.currentSong = prevSong;
  11672. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  11673. this.videoUrl = prevSong.filePath.replace(/ /g, '%20');
  11674. }else{
  11675. this.videoUrl = prevSong.filePath
  11676. }
  11677. this.cover = prevSong.pixelMapPath
  11678. this.artist = prevSong.artist
  11679. this.name = prevSong.name;
  11680. console.info('onecold startPlayOrResumePlay 11434')
  11681. this.startPlayOrResumePlay();
  11682. } else {
  11683. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  11684. if (this.curIndex === 0) {
  11685. this.curIndex = this.songList.length - 1;
  11686. } else {
  11687. this.curIndex--;
  11688. }
  11689. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11690. this.stop();
  11691. this.currentSong = this.songList[this.curIndex];
  11692. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  11693. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11694. }else{
  11695. this.videoUrl = this.songList[this.curIndex].filePath
  11696. }
  11697. this.artist = this.songList[this.curIndex].artist
  11698. this.name = this.songList[this.curIndex].name;
  11699. this.changeImageAnimation()
  11700. }
  11701. }
  11702. debounce() {
  11703. const delay = 600;
  11704. let cur = new Date().getTime();
  11705. if (cur - this.last > delay) {
  11706. this.last = cur;
  11707. return true;
  11708. }
  11709. return false;
  11710. }
  11711. /**
  11712. * Sets whether the screen is a constant based on the playback status.
  11713. */
  11714. watchStatus() {
  11715. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  11716. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11717. this.windowClass.setWindowKeepScreenOn(true);
  11718. } else {
  11719. this.windowClass.setWindowKeepScreenOn(false);
  11720. }
  11721. }
  11722. /**
  11723. * Volume gesture method onActionStart.
  11724. *
  11725. * @param event Gesture event.
  11726. */
  11727. private customDialogComponentIdMM: number = 0
  11728. @Builder
  11729. customDialogComponentMM() {
  11730. Column() {
  11731. Row() {
  11732. Blank()
  11733. Text('验证密码')
  11734. .fontSize(22)
  11735. .fontColor($r('app.color.pri_bg'))
  11736. .margin({ top: 18 })
  11737. Blank()
  11738. Image($r('app.media.close'))
  11739. .fillColor(Color.White)
  11740. .margin({ top: 18, right: 18 })
  11741. .width(20)
  11742. .onClick(() => {
  11743. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11744. })
  11745. }
  11746. .width('100%') // 使Row占据整个宽度
  11747. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  11748. Verify({
  11749. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  11750. });
  11751. }.height('60%')
  11752. .backgroundColor($r('app.color.index_background'))
  11753. .justifyContent(FlexAlign.SpaceBetween)
  11754. }
  11755. private handleVerifyCompleted(isSuccess: boolean) {
  11756. if (isSuccess) {
  11757. console.log('验证成功');
  11758. // 在这里处理验证成功后的逻辑
  11759. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11760. this.currentPath = this.lockPath
  11761. this.getSortedFiles(this.currentPath)
  11762. } else {
  11763. // console.log('验证失败');
  11764. ToastUtil.showToast('验证失败')
  11765. }
  11766. }
  11767. private showVerifyDialog() {
  11768. promptAction.openCustomDialog({
  11769. transition: TransitionEffect.asymmetric(
  11770. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  11771. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11772. ,
  11773. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  11774. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11775. ),
  11776. builder: () => {
  11777. this.customDialogComponentMM()
  11778. },
  11779. isModal: true,
  11780. autoCancel: true,
  11781. maskColor: Color.Transparent,
  11782. alignment: DialogAlignment.Bottom,
  11783. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  11784. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  11785. console.log("dialog onWillDismiss")
  11786. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  11787. dismissDialogAction.dismiss()
  11788. }
  11789. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  11790. dismissDialogAction.dismiss()
  11791. }
  11792. }
  11793. }).then((dialogId: number) => {
  11794. this.customDialogComponentIdMM = dialogId
  11795. })
  11796. }
  11797. //左滑操作 移动文件 重命名 删除等操作
  11798. @Builder
  11799. DeleteButton(item: VideoItem, index: number, filePath: string) {
  11800. Row() {
  11801. //加入收藏
  11802. Button() {
  11803. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  11804. .fillColor(Color.White)
  11805. .width(20)
  11806. }
  11807. .width(40)
  11808. .height(40)
  11809. .type(ButtonType.Circle)
  11810. .backgroundColor(this.themeColor)
  11811. .margin(5)
  11812. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11813. .onClick(() => {
  11814. if (item) {
  11815. this.doFav(item)
  11816. }
  11817. })
  11818. //加入下一首播放
  11819. Button() {
  11820. Image($r('app.media.next_to_play'))
  11821. .fillColor(Color.White)
  11822. .width(20)
  11823. }
  11824. .width(40)
  11825. .height(40)
  11826. .type(ButtonType.Circle)
  11827. .backgroundColor(this.themeColor)
  11828. .margin(5)
  11829. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11830. .onClick(() => {
  11831. this.addToNextPlay(item);
  11832. })
  11833. //复制文件
  11834. Button() {
  11835. Image($r('app.media.copy'))
  11836. .fillColor(Color.White)
  11837. .width(20)
  11838. }
  11839. .width(40)
  11840. .height(40)
  11841. .type(ButtonType.Circle)
  11842. .backgroundColor(this.themeColor)
  11843. .margin(5)
  11844. .id(filePath + 'copy')
  11845. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11846. .onClick(() => {
  11847. this.showCopyDialog(false, item, index, filePath + 'copy');
  11848. })
  11849. //移动文件
  11850. Button() {
  11851. Image($r('app.media.cut'))
  11852. .fillColor(Color.White)
  11853. .width(20)
  11854. }
  11855. .width(40)
  11856. .height(40)
  11857. .type(ButtonType.Circle)
  11858. .backgroundColor(this.themeColor)
  11859. .margin(5)
  11860. .id(filePath)
  11861. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11862. .onClick(() => {
  11863. this.showCutDialog(false, item, index, filePath);
  11864. })
  11865. Button() {
  11866. Image($r('app.media.cut_current'))
  11867. .fillColor(Color.White)
  11868. .width(20)
  11869. }
  11870. .width(40)
  11871. .height(40)
  11872. .type(ButtonType.Circle)
  11873. .backgroundColor(this.themeColor)
  11874. .margin(5)
  11875. .id(filePath + 'current')
  11876. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  11877. (this.isHasDir ? Visibility.Visible : Visibility.None))
  11878. .onClick(() => {
  11879. this.showCutDialog(true, item, index, filePath + 'current');
  11880. })
  11881. //重命名
  11882. Button() {
  11883. Image($r('app.media.rename2'))
  11884. .fillColor(Color.White)
  11885. .width(20)
  11886. }
  11887. .width(40)
  11888. .height(40)
  11889. .type(ButtonType.Circle)
  11890. .backgroundColor(this.themeColor)
  11891. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11892. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11893. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11894. .margin(5)
  11895. .onClick(() => {
  11896. this.showReNameDialog(item, index + '', filePath)
  11897. })
  11898. Button() {
  11899. Image($r('app.media.delete2'))
  11900. .fillColor(Color.White)
  11901. .width(20)
  11902. }
  11903. .width(40)
  11904. .height(40)
  11905. .type(ButtonType.Circle)
  11906. .backgroundColor(this.themeColor)
  11907. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11908. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11909. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11910. .margin(5)
  11911. .onClick(() => {
  11912. this.selectedFiles.push(item)
  11913. this.showWarnIsDelete()
  11914. // this.showWarnIsDeleteFile(item, index + '', filePath)
  11915. })
  11916. Button() {
  11917. Image($r('app.media.share2'))
  11918. .fillColor(Color.White)
  11919. .width(20)
  11920. }
  11921. .width(40)
  11922. .height(40)
  11923. .type(ButtonType.Circle)
  11924. .backgroundColor(this.themeColor)
  11925. .margin(5)
  11926. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11927. .onClick(() => {
  11928. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11929. })
  11930. }
  11931. }
  11932. /**
  11933. * 穿山甲banner广告
  11934. */
  11935. // private declare bannerAd: CSJNativeExpressAd;
  11936. // @State private status: string = "未加载"
  11937. // @State private isShowAd: boolean = false
  11938. // private declare mAdSlot: AdSlot;
  11939. // private mBiddingAdm = '' //服务端bidding才需要设置
  11940. // private expressLoadAdListener: NativeExpressAdListener = {
  11941. // /**
  11942. // * 加载失败的回调
  11943. // *
  11944. // * @param code
  11945. // * @param message
  11946. // */
  11947. // onError: (code: number, message: string) => {
  11948. // console.error("加载广告失败,code=" + code + ",message=" + message);
  11949. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  11950. // },
  11951. //
  11952. // /**
  11953. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  11954. // *
  11955. // * @param ads 返回的广告列表
  11956. // */
  11957. //
  11958. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  11959. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  11960. // if (ads && ads.length > 0) {
  11961. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  11962. // ad.setExpressInteractionListener({
  11963. // /**
  11964. // *广告的点击回调
  11965. // * @param type 广告的交互类型
  11966. // */
  11967. // onAdClicked: (type: number) => {
  11968. // console.log("BannerExpressAdPage==onAdClicked......");
  11969. // },
  11970. //
  11971. // /**
  11972. // * 广告的展示回调 每个广告仅回调一次
  11973. // * @param type 广告的交互类型
  11974. // */
  11975. // onAdShow: (type: number) => {
  11976. // console.log("BannerExpressAdPage==onAdShow......");
  11977. // },
  11978. //
  11979. // /**
  11980. // * 模板渲染失败
  11981. // */
  11982. // onRenderFail: (code: number, msg: string) => {
  11983. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  11984. // },
  11985. //
  11986. // /**
  11987. // * 模板渲染成功
  11988. // * @param width 返回view的宽 单位 vp
  11989. // * @param height 返回view的高 单位 vp
  11990. // */
  11991. // onRenderSuccess: (width: number, height: number) => {
  11992. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  11993. // this.bannerAd = ad;
  11994. // this.status = "广告加载完成待展示";
  11995. //
  11996. // this.showBannerAd()
  11997. // }
  11998. // })
  11999. // //渲染广告
  12000. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  12001. // this.setDislikeCallback(ad); //设置dislike
  12002. // ad.render(this.getUIContext())
  12003. // this.status = "广告加载中...";
  12004. // });
  12005. // }
  12006. // }
  12007. // }
  12008. //
  12009. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  12010. // ad.setDislikeCallback({
  12011. // /**
  12012. // * dislike show
  12013. // */
  12014. // onShow: () => {
  12015. // console.log("BannerExpressAdPage==dislike......show");
  12016. // },
  12017. //
  12018. // /**
  12019. // * @param position 选择的位置
  12020. // * @param value 选择的内容
  12021. // * @param enforceRemove 是否强制关闭广告
  12022. // */
  12023. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  12024. // this.isShowAd = false;
  12025. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  12026. // ",enforce=" + enforceRemove);
  12027. // },
  12028. //
  12029. // /**
  12030. // * 点击取消
  12031. // */
  12032. // onCancel: () => {
  12033. // console.log("BannerExpressAdPage==dislike......onCancel");
  12034. // }
  12035. //
  12036. // })
  12037. // }
  12038. /**
  12039. * 加载Banner广告
  12040. */
  12041. loadBannerAd(rit: string) {
  12042. // if (Utility.isNoble()) {
  12043. // return
  12044. // }
  12045. // if (!Utility.isPassInstallTime(2)) {
  12046. // return
  12047. // }
  12048. // this.isShowAd = false;
  12049. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  12050. // this.mAdSlot = new AdSlotBuilder()
  12051. // .setCodeId(rit)
  12052. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  12053. // .setAdCount(1)
  12054. // .setBidAdm(this.mBiddingAdm)
  12055. // .build()
  12056. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  12057. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  12058. // this.status = "广告加载中..."
  12059. }
  12060. /**
  12061. * 展示Banner广告
  12062. */
  12063. // showBannerAd() {
  12064. // if (!this.bannerAd) {
  12065. // return
  12066. // }
  12067. // this.isShowAd = true
  12068. // this.status = "已展示"
  12069. // }
  12070. /**
  12071. * 穿山甲广告代码结束
  12072. */
  12073. /**
  12074. * 处理歌单播放请求
  12075. */
  12076. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  12077. string, songFilePaths: string[], startIndex: number) {
  12078. try {
  12079. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  12080. // 检查是否为WebDAV播放请求
  12081. if (playlistId === 'webdav-playlist') {
  12082. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  12083. // 从全局内存读取videoItems数据
  12084. const videoItems = getWebdavVideoItems();
  12085. const currentPlayIndex = getWebdavCurrentPlayIndex();
  12086. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  12087. if (videoItems && videoItems.length > 0) {
  12088. // 验证webdav_account_id设置情况
  12089. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  12090. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  12091. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  12092. return
  12093. } else {
  12094. return
  12095. }
  12096. }
  12097. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  12098. const songMap: Map<number, VideoItem> = new Map()
  12099. let completedQueries = 0
  12100. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  12101. // 遍历所有文件路径,使用索引记录位置
  12102. for (let i = 0; i < songFilePaths.length; i++) {
  12103. const filePath = songFilePaths[i]
  12104. const index = i
  12105. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  12106. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  12107. const queryPromise = this.table.queryVideoByFilePath(filePath)
  12108. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  12109. queryPromise.then((videoItem) => {
  12110. completedQueries++
  12111. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  12112. if (videoItem) {
  12113. // 使用索引作为key保存到Map中,保持原始顺序
  12114. songMap.set(index, videoItem)
  12115. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  12116. } else {
  12117. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  12118. }
  12119. // 检查是否所有歌曲都已加载完成
  12120. if (completedQueries === songFilePaths.length) {
  12121. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  12122. // 按照索引顺序重建歌曲数组
  12123. const songs: VideoItem[] = []
  12124. for (let j = 0; j < songFilePaths.length; j++) {
  12125. const song = songMap.get(j)
  12126. if (song) {
  12127. songs.push(song)
  12128. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  12129. }
  12130. }
  12131. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  12132. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12133. }
  12134. }).catch((error: Error) => {
  12135. completedQueries++
  12136. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  12137. // 即使出错也要检查是否完成所有查询
  12138. if (completedQueries === songFilePaths.length) {
  12139. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  12140. // 按照索引顺序重建歌曲数组
  12141. const songs: VideoItem[] = []
  12142. for (let j = 0; j < songFilePaths.length; j++) {
  12143. const song = songMap.get(j)
  12144. if (song) {
  12145. songs.push(song)
  12146. }
  12147. }
  12148. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12149. }
  12150. })
  12151. }
  12152. } catch (error) {
  12153. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  12154. ToastUtil.showToast('播放失败')
  12155. }
  12156. }
  12157. /**
  12158. * 完成歌单加载并开始播放
  12159. */
  12160. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  12161. if (songs.length === 0) {
  12162. Logger.error('heanup 没有找到任何可播放的歌曲')
  12163. ToastUtil.showToast('没有找到可播放的歌曲')
  12164. return
  12165. }
  12166. this.songList = songs
  12167. this.sonDataSource.pushArrayData(songs)
  12168. this.sonDataSource.notifyDataReload()
  12169. this.curIndex = startIndex
  12170. if (songs[startIndex]) {
  12171. // 确保当前播放的歌曲也更新到存储
  12172. AppStorage.setOrCreate('currentSong', songs[startIndex])
  12173. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  12174. this.doPlay(songs[startIndex], startIndex, true)
  12175. }
  12176. PreferencesUtil.putSync('LastMusicList', this.songList)
  12177. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  12178. }
  12179. }
  12180. //视频气泡窗口的布局
  12181. @Builder
  12182. function customPopupBuilder(dataBu: BubbleBean) {
  12183. List() {
  12184. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  12185. ListItem() {
  12186. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12187. Row() {
  12188. Column() {
  12189. Image(dataBu.imageRes[index])
  12190. .height(28)
  12191. .fillColor(dataBu.color)
  12192. .alignSelf(ItemAlign.Center)
  12193. }
  12194. .width(32)
  12195. Text(item)
  12196. .padding({
  12197. top: 10,
  12198. bottom: 10,
  12199. right: 10,
  12200. left: 10
  12201. })
  12202. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  12203. .textAlign(TextAlign.Start)
  12204. .width("100%")
  12205. }
  12206. }
  12207. .backgroundColor($r('app.color.settings_background_main'))
  12208. .margin({ top: 6, bottom: 6 })
  12209. }
  12210. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12211. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  12212. TransitionEffect.scale({ x: 0, y: 0 })))
  12213. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12214. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12215. .onClick(() => {
  12216. dataBu.onItemClick?.(index)
  12217. })
  12218. })
  12219. }
  12220. .scrollBar(BarState.Off)
  12221. .width(120)
  12222. .divider({
  12223. strokeWidth: 1,
  12224. color: "#22FFFFFF"
  12225. })
  12226. }
  12227. // Function to calculate a hash for the file list
  12228. function simpleHash(fileList: string[]): string {
  12229. let hash = 0;
  12230. const str = fileList.join(',');
  12231. for (let i = 0; i < str.length; i++) {
  12232. const char = str.charCodeAt(i);
  12233. hash = (hash << 5) - hash + char;
  12234. hash |= 0; // Convert to 32bit integer
  12235. }
  12236. return hash.toString();
  12237. }
  12238. interface MoreItem {
  12239. id: number;
  12240. image: Resource;
  12241. title: string;
  12242. }
  12243. //视频气泡窗口的布局
  12244. @Builder
  12245. function cutPopupBuilder(dataBu: BubbleBean) {
  12246. Column() {
  12247. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  12248. .padding({
  12249. top: 10,
  12250. bottom: 10,
  12251. right: 10,
  12252. left: 10
  12253. })
  12254. .textAlign(TextAlign.Start)
  12255. .width(160)
  12256. .fontWeight(666)
  12257. .fontSize(16)
  12258. List() {
  12259. ForEach(dataBu.data, (item: string, index: number) => {
  12260. ListItem() {
  12261. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12262. Row() {
  12263. Column() {
  12264. Image($r('app.media.music_group'))
  12265. .height(28)
  12266. .fillColor(dataBu.color)
  12267. .alignSelf(ItemAlign.Center)
  12268. }
  12269. .width(32)
  12270. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  12271. .padding({
  12272. top: 10,
  12273. bottom: 10,
  12274. right: 10,
  12275. left: 10
  12276. })
  12277. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  12278. .fontSize(15)
  12279. }
  12280. }
  12281. .backgroundColor(Color.Transparent)
  12282. .margin({ top: 7, bottom: 7 })
  12283. }
  12284. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12285. .animation({ duration: 500 }),
  12286. TransitionEffect.scale({ x: 0, y: 0 })))
  12287. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12288. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12289. .onClick(() => {
  12290. dataBu.onItemClick?.(index)
  12291. })
  12292. })
  12293. }
  12294. .scrollBar(BarState.Off)
  12295. .width(150)
  12296. .divider({
  12297. strokeWidth: 1,
  12298. color: "#22FFFFFF"
  12299. })
  12300. }
  12301. .height(300)
  12302. .padding({
  12303. bottom: 30
  12304. })
  12305. }
  12306. function getFileDirName(filePath: string,rootPath:string): string{
  12307. if(filePath===rootPath){
  12308. return '首页'
  12309. }
  12310. let result = FileUtil.getFileName(filePath)
  12311. if(StrUtil.isEmpty(result))
  12312. return ''
  12313. if(result.startsWith('.'))
  12314. result = result.replace(/\./g, '')
  12315. return result
  12316. }
  12317. //只扫描当前目录下文件(不扫描子文件夹)的方法
  12318. @Concurrent
  12319. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  12320. const table: MediaTable = new MediaTable(context);
  12321. try {
  12322. // 直接获取当前目录下的文件列表
  12323. const files = FileUtil.listFileSync(dirPath);
  12324. await Promise.all(files.map(async (file) => {
  12325. const fPath = `${dirPath}/${file}`;
  12326. // 跳过目录,只处理文件
  12327. if (FileUtil.isDirectory(fPath)) {
  12328. return;
  12329. }
  12330. // 跳过特定格式文件
  12331. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  12332. return;
  12333. }
  12334. // 检查是否为媒体文件
  12335. if (Utility.isMeidaByExtension(fPath)) {
  12336. let mType = CommonConstants.TYPE_LOCAL;
  12337. if (fPath.includes(lockPath)) {
  12338. mType = CommonConstants.TYPE_LOCK;
  12339. }
  12340. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  12341. context, fPath, mType, true
  12342. );
  12343. table.insert(mediaItem, (id: number) => {
  12344. // 插入回调函数
  12345. }, cover_api);
  12346. }
  12347. }));
  12348. } catch (error) {
  12349. console.error(' 扫描当前目录失败:', error);
  12350. }
  12351. }