LocalMusic.ets 483 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859
  1. import TitleBar from './TitleBar'
  2. import { curves, display, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,borderRadiuses, SegmentButtonOptions } from '@kit.ArkUI';
  5. import {
  6. AppUtil,
  7. ArrayUtil,
  8. Base64Util,
  9. DateUtil,
  10. DeviceUtil,
  11. DisplayUtil,
  12. FileUtil,
  13. GlobalContext,
  14. ImageUtil,
  15. LogUtil,
  16. MD5,
  17. PreferencesUtil,
  18. RandomUtil,
  19. StrUtil,
  20. ToastUtil
  21. } from '@pura/harmony-utils';
  22. import { imagePathToPixelMap } from '../common/util/CommUtils';
  23. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  24. import { CommonConstants } from '../common/constants/CommonConstants';
  25. import { EventConstants } from '../common/constants/EventConstants';
  26. import Logger from '../common/util/Logger';
  27. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  28. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  29. import { BubbleBean } from '../viewmodel/BubbleBean';
  30. import { PopupPosition, XPopup } from '@chinalike/popup';
  31. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  32. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  33. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  34. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  35. import Base64 from '@ohos.util';
  36. import { Verify } from './Verify';
  37. import { taskpool } from '@kit.ArkTS';
  38. import { RotatingCover } from './RotatingCover';
  39. import { PlayConstants } from '../common/constants/PlayConstants';
  40. import { effectKit } from '@kit.ArkGraphics2D';
  41. import { ColorConversion } from '../common/util/ColorConversion';
  42. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  43. import { AvSessionController } from '../controller/AvSessionController';
  44. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  45. import { FFMpegTags,Utility } from '../common/util/Utility';
  46. import { TagsContentCover } from '../view/TagsContentCover';
  47. import { ImageFancyModifier } from '../common/util/AttributeModifierUtil'
  48. import {
  49. // DeviceChangeReason,
  50. IjkMediaPlayer,
  51. InterruptEvent,
  52. InterruptHintType,
  53. LogUtils,
  54. OnBufferingUpdateListener,
  55. OnCompletionListener,
  56. OnErrorListener,
  57. OnInfoListener,
  58. OnPreparedListener,
  59. OnSeekCompleteListener,
  60. OnTimedTextListener,
  61. OnVideoSizeChangedListener
  62. } from '@ohos/ijkplayer';
  63. import { PlayStatus } from '../common/PlayStatus';
  64. import fs from '@ohos.file.fs';
  65. import { image } from '@kit.ImageKit';
  66. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  67. import { UniversalDetector } from '@ohos/juniversalchardet';
  68. import { SettingPage } from '../pages/SettingPage';
  69. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  70. import { CommonConstants2 } from '../common/util/CommonConstants2';
  71. import { hilog } from '@kit.PerformanceAnalysisKit';
  72. import { LazyDataSource } from '../common/util/LazyDataSource';
  73. import MediaTable from '../common/util/MediaTable';
  74. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  75. import ImageUtils from '../common/util/ImageUtils';
  76. import { ringtone } from '@kit.RingtoneKit';
  77. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  78. import { resourceManager } from '@kit.LocalizationKit';
  79. import { deviceInfo } from '@kit.BasicServicesKit';
  80. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  81. import app from '@system.app';
  82. import { TextNodeController } from './PipLyricTextBuilder';
  83. import { IndexerView } from './IndexerView';
  84. import { KeyCode } from '@kit.InputKit';
  85. import { KnockController } from '../controller/KnockController';
  86. import { DeleteComptent } from '../view/DeleteComptent';
  87. import { ABLoopComptent } from '../view/ABLoopComptent';
  88. import { FixMessyView } from '../view/FixMessyView';
  89. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  90. import { CueComptent } from '../view/CueComptent';
  91. import PlaylistTable from '../common/util/PlaylistTable';
  92. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  93. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  94. import { convertPlaylistSongsToVideoItems, emptyView } from '../pages/PlaylistDetailPage';
  95. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  96. import { Song } from '../viewmodel/Song';
  97. import { SongType } from '../common/enums/SongType';
  98. import { WebdavManager, WebDavAuthInfo as WebDavManagerAuthInfo } from '../common/util/WebdavManager';
  99. const TAG = 'LocalMusic';
  100. /**
  101. * 歌单播放事件数据
  102. */
  103. interface PlaylistEventData {
  104. playlistId: string;
  105. playlistName: string;
  106. songCount: number;
  107. startIndex: number;
  108. songFilePaths: string[];
  109. webDavAuthInfo?: WebDavAuthInfo; // 新增WebDAV认证信息
  110. }
  111. /**
  112. * WebDAV认证信息(LocalMusic专用)
  113. */
  114. interface WebDavAuthInfo {
  115. accountId: number;
  116. host: string;
  117. port: number;
  118. account: string;
  119. password: string;
  120. enableHttps: boolean;
  121. }
  122. const DEFAULT_INDEX =
  123. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  124. 'X', 'Y', 'Z']
  125. //排序类型
  126. function getTypeOrder(type: number) {
  127. switch (type) {
  128. case CommonConstants.TYPE_IS_DIR:
  129. return 1; // First
  130. case CommonConstants.TYPE_IS_CSJAD:
  131. return 2; // Middle
  132. case CommonConstants.TYPE_LOCAL:
  133. return 3; // Last
  134. default:
  135. return 4; // Unknown types, if any, go last
  136. }
  137. }
  138. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  139. // 定义接口
  140. interface HiCarAspectRatio {
  141. ratio: number;
  142. name: string;
  143. }
  144. interface GeneratedObjectLiteralInterface_1 {
  145. assetId: string;
  146. title: string;
  147. artist: string;
  148. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  149. mediaUri: string;
  150. // 该字段大写,音频'AUDIO',视频'VIDEO'
  151. mediaType: string;
  152. mediaSize: number;
  153. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  154. startPosition: number;
  155. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  156. duration: number;
  157. albumCoverUri: string;
  158. albumTitle: string;
  159. appName: string;
  160. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  161. drmScheme: string;
  162. }
  163. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  164. const ITEM_HEIGHT: number = 65; // 列表项中高度
  165. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  166. //功能强大的音乐播放器
  167. @Preview
  168. @Component
  169. export struct LocalMusic {
  170. @State offHeight: number = 75
  171. @State currentSongList: Array<VideoItem> = []//当前歌单
  172. @Consume currentSongListName:string //当前歌单名称
  173. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  174. @State isRefreshing: boolean = false;
  175. @State maxRefreshingHeight: number = 100.0;
  176. private contentNode?: ComponentContent<Object> = undefined;
  177. @State ratioL: number = 1;
  178. @State mediaKuCount: number = 0;
  179. @State albumCount: number = 0;
  180. @State artistCount: number = 0;
  181. @State fastForwardSeconds: string = '10'
  182. @State isShowBackFast: boolean = true//快进快退按钮
  183. @State isCanAuto:boolean = true
  184. @State opacityValueImage: number = 1;
  185. @State tipPopup:boolean = false
  186. @Consume mType: number;
  187. @StorageProp('themeColor') themeColor: string =
  188. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  189. themeMode: number = 0;
  190. @State titleName: string = '首页'
  191. @State textStr: string = ''
  192. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  193. // private download_path: string = '';
  194. @Consume rootPath: string //音频根目录
  195. @Consume currentPath: string
  196. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  197. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  198. @State lockPath: string = ''
  199. @State favPath: string = ''
  200. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  201. @State historyPath: string = ''
  202. @State historyList: Array<VideoItem> = []
  203. @Consume isHistory: boolean
  204. static readonly HISTORY_MUSIC: string = 'music_historyList';
  205. private table: MediaTable = new MediaTable(getContext(this))
  206. private playlistTable: PlaylistTable | null = null
  207. @State allPlaylists: Playlist[] = []
  208. @State isZero: boolean = false
  209. @State fileList: Array<string> = []
  210. @State dirList: Array<VideoItem> = []
  211. @Consume videoLocalList: Array<VideoItem>
  212. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  213. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  214. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  215. @State artistList: Array<VideoItem> = []; //艺术家文件
  216. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  217. @State albumList: Array<VideoItem> = []; //专辑文件
  218. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  219. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  220. @State imageOpacities: number[] = [];
  221. @Consume isCanBack: boolean
  222. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  223. @State showSingleLyric: boolean = false
  224. @State sortType: number = 4 //默认排序方式
  225. @State isShowSimi: boolean = false //是否显示私密音频
  226. @State isShowFAV: boolean = true //是否显示我的收藏
  227. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  228. @State isShowAllBar: boolean = true //是否显示播放全部条
  229. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  230. @State isShowHistory: boolean = true //是否显示最近播放
  231. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  232. @State isGridMusic: boolean = false //是否网格布局
  233. @State isCircleBtn: boolean = false //是否圆形播放按钮
  234. @State twoFingerType: number = 3 //双支放大缩小的类型
  235. @State isScrollHide: boolean = false //是否滚动隐藏
  236. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  237. @State isStartAutoPlay: boolean = false //启动后自动播放
  238. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  239. @State isShowHeader: boolean = true
  240. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  241. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  242. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  243. @State isSwipe: boolean = false //listItem的左滑开关
  244. @State openSkipSongAnimate: boolean = true//切歌动画效果
  245. @State customizeBgPath: string | undefined = '';
  246. @State isDarkMode: boolean = false
  247. @State lyricTextWeight: number = 400
  248. @State lyricTextWeightPip: number = 400
  249. @State currentSwiperIndex: number = 0
  250. @State blurValue: number = 0 //背景模糊
  251. @State bgBrightness: number = 0 //背景亮度
  252. private listScroller: ListScroller = new ListScroller()
  253. private playListScroller: Scroller = new Scroller()
  254. @State isOneKeyTags:boolean = false
  255. @State isFixMessy:boolean = false
  256. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  257. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  258. @StorageProp('bottomRectHeight') bottomRectHeight: number = 0;
  259. @StorageProp('windowWidth') windowWidth: number = 0;
  260. @StorageProp('windowHeight') windowHeight: number = 0;
  261. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  262. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  263. private UNKONWN:string = '';
  264. private listArea: Area = {
  265. width: 0,
  266. height: 0,
  267. position: {},
  268. globalPosition: {}
  269. }
  270. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  271. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  272. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  273. private currentWebDavAuthInfo: WebDavAuthInfo | null = null;
  274. //瀑布流的列数横竖屏动态切换
  275. onIsLandscapeChange() {
  276. if(this.isLandscape){
  277. this.columns = 4
  278. }else{
  279. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  280. }
  281. }
  282. onColorModeChange() {
  283. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  284. if (this.isCustomizeBg) {
  285. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  286. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  287. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  288. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  289. this.tabOptions.selectedBackgroundColor = Color.Transparent
  290. } else {
  291. if (!this.isDarkMode) {
  292. this.titleBarModel.setTitleBarBackground(this.themeColor)
  293. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  294. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  295. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  296. this.tabOptions.selectedBackgroundColor = this.themeColor
  297. } else {
  298. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  299. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  300. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  301. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  302. this.tabOptions.selectedBackgroundColor = $r('app.color.silvery')
  303. }
  304. }
  305. }
  306. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  307. onTopBarhange(){
  308. if(this.isShowTitleBar){
  309. console.log('onecold 导航条显示')
  310. this.topBarHeight = 50
  311. this.offHeight = 75
  312. }else{
  313. console.log('onecold 导航条隐藏')
  314. this.topBarHeight = 0
  315. if(this.twoFingerType!=4){
  316. this.offHeight = 30
  317. }
  318. }
  319. }
  320. //点击某个歌单id发生变化的时候回调
  321. onIDChange(){
  322. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  323. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  324. if(this.modeType==4){
  325. this.isShowTitleBar = false
  326. this.titleBarModel.setTitleName(this.currentSongListName)
  327. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  328. //获取缓存
  329. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  330. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  331. if(StrUtil.isNotEmpty(cacheSongs)){
  332. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  333. this.updateListData(this.currentSongList, true)
  334. }
  335. this.doSongListTask()//获取歌单信息
  336. }
  337. }
  338. async doSongListTask() {
  339. // 初始化歌单数据库
  340. const playlistTable = new PlaylistTable(this.context);
  341. // 查询歌单中的所有歌曲
  342. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  343. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  344. if (ArrayUtil.isEmpty(playlistSongs)) {
  345. this.updateListData([], true)
  346. } else {
  347. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  348. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  349. this.updateListData(this.currentSongList, true)
  350. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  351. // 只保存前100条记录到缓存中
  352. let canceList = this.currentSongList.slice(0, 100);
  353. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  354. JSON.stringify(canceList))
  355. } else {
  356. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  357. }
  358. }
  359. }
  360. onModeChange() {
  361. this.isFavMusic = false
  362. if (this.modeType === 2 || this.modeType === 3|| this.modeType === 4) {
  363. this.titleBarModel.setRightIcon(null)
  364. } else {
  365. this.titleBarModel.setRightIcon(($r('app.media.add')))
  366. }
  367. LogUtil.info('onecold onModeChange = ' + this.modeType)
  368. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  369. switch (this.modeType) {
  370. case 0:
  371. this.getSortedFiles(this.currentPath)
  372. break
  373. case 1:
  374. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  375. this.updateListData(this.mediaKuList)
  376. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  377. break
  378. case 2:
  379. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  380. this.updateListData(this.artistList)
  381. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  382. break
  383. case 3:
  384. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  385. this.updateListData(this.albumList)
  386. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  387. break
  388. }
  389. }
  390. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  391. // @StorageLink('isPlay') isPlay: boolean = false;
  392. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  393. @StorageLink('songList') songList: Array<VideoItem> = [];
  394. @State translateY: number = 0;
  395. @State isShowSheet: boolean = false;
  396. @State isShowSheetView: boolean = false;
  397. @State isShowTimeCloseView: boolean = false;
  398. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  399. @StorageLink('currIndex') curIndex: number = 0;
  400. @Consume isShowDrawer: boolean;
  401. @Consume offsetX: number;
  402. @State isFac: boolean = false;
  403. @State favList: Array<VideoItem> = []
  404. @Consume isFavMusic: boolean
  405. @State isClickedPLayAll: boolean = false;
  406. private scrollerForlist: ListScroller = new ListScroller();
  407. private knockController: KnockController | undefined = undefined;
  408. imagesF: ImageFrameInfo[] = [
  409. { src: $r("app.media.app_loading0") },
  410. { src: $r("app.media.app_loading1") },
  411. { src: $r("app.media.app_loading2") },
  412. { src: $r("app.media.app_loading3") },
  413. ]
  414. @State animationState: AnimationStatus = AnimationStatus.Initial
  415. // 缓存机制
  416. private cache: Map<string, Array<VideoItem>> = new Map();
  417. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  418. // 持久化缓存
  419. private async saveCacheToStorage() {
  420. const cacheArray = Array.from(this.cache.entries());
  421. const stringCacheArray = Array.from(this.stringCache.entries());
  422. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  423. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  424. }
  425. // 载入缓存
  426. private async loadCacheFromStorage() {
  427. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  428. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  429. if (cacheString) {
  430. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  431. this.cache = new Map(cacheArray);
  432. }
  433. if (stringCacheString) {
  434. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  435. this.stringCache = new Map(stringCacheArray);
  436. }
  437. }
  438. // 查找缓存
  439. private findCache(key: string): Array<VideoItem> | undefined {
  440. return this.cache.get(key);
  441. }
  442. // 查找字符串缓存
  443. private findStringCache(key: string): string | undefined {
  444. return this.stringCache.get(key);
  445. }
  446. // 添加缓存
  447. private addCache(key: string, value: Array<VideoItem>) {
  448. this.cache.set(key, value);
  449. }
  450. // 添加字符串缓存
  451. private addStringCache(key: string, value: string) {
  452. this.stringCache.set(key, value);
  453. }
  454. // 删除缓存
  455. private deleteCache(key: string) {
  456. this.cache.delete(key);
  457. this.saveCacheToStorage()
  458. }
  459. // 删除字符串缓存
  460. private deleteStringCache(key: string) {
  461. this.stringCache.delete(key);
  462. }
  463. // 多选机制
  464. @State selectedFiles: Array<VideoItem> = [];
  465. @State isMultiSelect: boolean = false;
  466. @State isAllSelected: boolean = false;
  467. @State appName: string = ''
  468. @State isHasDir: boolean = false
  469. @State packName: string = ''
  470. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  471. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  472. .setTitleTextStyle(FontStyle.Normal)
  473. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  474. .setLeftIcon($r('app.media.menu'))
  475. .setLeftIconWidth(26)
  476. .setLeftIconHeight(26)
  477. .setTitleName('首页')
  478. .setTitleBarMinHeight(55)
  479. .setTitleFontSize(18)
  480. .setTitleFontColor(Color.White)
  481. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  482. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  483. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  484. .setRightIcon($r('app.media.add'))
  485. .setOnRightClickListener(() => {
  486. this.showSheelDialog()
  487. })
  488. // .setOnTitleClickListener(() => {
  489. // this.showPupDialog()
  490. // })
  491. .setOnLeftClickListener(() => {
  492. this.doSwipBack()
  493. })
  494. doSwipBack() {
  495. this.isZero = false
  496. if (this.modeType !== 0 && this.isCanBack) {
  497. this.onModeChange()
  498. this.isCanBack = false
  499. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  500. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  501. setTimeout(() => {
  502. if (this.modeType == 2) {
  503. if (this.isGridMusic||this.twoFingerType==4) {
  504. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  505. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  506. if(this.twoFingerType==4){
  507. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  508. }else{
  509. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  510. }
  511. } else {
  512. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  513. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  514. }
  515. } else if (this.modeType == 3) {
  516. if (this.isGridMusic||this.twoFingerType==4) {
  517. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  518. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  519. if(this.twoFingerType==4){
  520. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  521. }else{
  522. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  523. }
  524. } else {
  525. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  526. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  527. }
  528. }
  529. }, 200)
  530. return
  531. }
  532. if (this.isHistory || this.isFavMusic) {
  533. this.isHistory = false
  534. this.getSortedFiles(this.currentPath)
  535. return
  536. }
  537. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  538. animateTo({ duration: 555 }, () => {
  539. // 动画闭包内控制Image组件的出现和消失
  540. this.isShowDrawer = !this.isShowDrawer
  541. this.offsetX = 0
  542. })
  543. return
  544. }
  545. //返回上一级歌单的滚动位置
  546. setTimeout(() => {
  547. if (this.modeType == 0) {
  548. if (this.isGridMusic||this.twoFingerType==4) {
  549. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  550. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  551. if(this.twoFingerType==4){
  552. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  553. }else{
  554. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  555. }
  556. } else {
  557. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  558. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  559. }
  560. }
  561. }, 300)
  562. this.currentPath = Utility.getParentDirectory(this.currentPath)
  563. Logger.info('this.currentPath2 = ' + this.currentPath)
  564. this.getSortedFiles(this.currentPath)
  565. }
  566. // 组件生命周期
  567. aboutToAppear() {
  568. // 初始化 PlaylistTable
  569. this.playlistTable = new PlaylistTable(getContext(this))
  570. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  571. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  572. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  573. this.tipPopup = !this.tipPopup
  574. PreferencesUtil.putSync('isFirstTiped',false)
  575. }
  576. this.initSetting()
  577. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  578. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  579. Utility.getAppName(getContext(this)).then((appName: string) => {
  580. this.appName = appName
  581. })
  582. this.packName = AppUtil.getBundleName()
  583. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  584. this.loadCacheFromStorage(); // 加载文件夹缓存
  585. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  586. this.initLoadCache()
  587. this.mkDownLoadDir()
  588. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  589. // 监听广播事件(打开其他应用处理)
  590. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  591. this.saveVideoDatas([eventData.data?.message], true)
  592. });
  593. //侧滑广播接收时间
  594. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  595. // 监听广播事件(打开其他应用处理)
  596. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  597. animateTo({ duration: 555 }, () => {
  598. this.doSwipBack()
  599. })
  600. });
  601. //ScanFilePage广播接收时间
  602. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  603. // 监听ScanFilePage广播事件(更新数据库)
  604. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  605. this.doUpdateData()
  606. });
  607. // 监听歌单播放请求事件
  608. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  609. emitter.on(eventPlaylistPlay, (eventData: emitter.EventData) => {
  610. Logger.info('heanup eventPlaylistPlay received - full eventData: ' + JSON.stringify(eventData))
  611. Logger.info('heanup eventPlaylistPlay received - eventData.data: ' + JSON.stringify(eventData.data))
  612. const data = eventData.data as Record<string, Object>
  613. if (!data) {
  614. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  615. return
  616. }
  617. // 检查歌单播放数据结构
  618. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  619. Logger.info('heanup eventPlaylistPlay: 接收到歌单播放数据')
  620. // 提取WebDAV认证信息(如果存在)
  621. let webDavAuthInfo: WebDavAuthInfo | undefined = undefined;
  622. if (data.webDavAuthInfo) {
  623. // 将webDavAuthInfo转换为正确的类型
  624. const authData = data.webDavAuthInfo as Record<string, Object>;
  625. webDavAuthInfo = {
  626. accountId: authData.accountId as number,
  627. host: authData.host as string,
  628. port: authData.port as number,
  629. account: authData.account as string,
  630. password: authData.password as string,
  631. enableHttps: authData.enableHttps as boolean
  632. };
  633. Logger.info(`heanup 从事件中获取到WebDAV认证信息,账户ID: ${webDavAuthInfo.accountId}`);
  634. }
  635. // 手动构建数据对象以避免类型转换问题
  636. const playlistData: PlaylistEventData = {
  637. playlistId: data.playlistId as string,
  638. playlistName: data.playlistName as string,
  639. songCount: data.songCount as number,
  640. startIndex: data.startIndex as number,
  641. songFilePaths: data.songFilePaths as string[]
  642. }
  643. // 根据文件路径重新构建歌曲列表,并传递WebDAV认证信息
  644. this.handlePlaylistPlayRequest(
  645. playlistData.playlistId,
  646. playlistData.playlistName,
  647. playlistData.songFilePaths,
  648. playlistData.startIndex,
  649. webDavAuthInfo
  650. )
  651. return
  652. }
  653. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  654. });
  655. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  656. // 监听广播事件(通用设置配置更新)
  657. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  658. this.doChangeSetting()
  659. });
  660. let event: Callback<InterruptEvent> = (event) => {
  661. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  662. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  663. this.savePlaybackPosition()
  664. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  665. this.pause();
  666. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  667. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  668. console.info('onecold startPlayOrResumePlay 514')
  669. this.startPlayOrResumePlay();
  670. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  671. this.stop();
  672. }
  673. }
  674. this.mIjkMediaPlayer.on('audioInterrupt', event);
  675. // 音频设备断连回调处理
  676. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  677. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  678. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  679. // this.pause();
  680. // }
  681. // }
  682. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  683. this.makeWorker()
  684. //折叠屏的屏幕显示模式变化
  685. display.on('foldDisplayModeChange', (data) => {
  686. this.doChangeBarHeight()
  687. });
  688. display.on('foldStatusChange', (data) => {
  689. Logger.info('onecold foldStatusChange ')
  690. });
  691. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  692. // 读取 themeMode 并同步 currentColorMode
  693. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  694. this.applyThemeMode(this.themeMode)
  695. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  696. AppStorage.setOrCreate('themeColor', themeColor);
  697. this.themeColor = themeColor;
  698. this.doChangeSetting()
  699. this.windowClass.on('windowSizeChange', (size) => {
  700. LogUtil.info('onecold windowSizeChange')
  701. this.doChangeBarHeight()
  702. let viewWidth = px2vp(size.width);
  703. let viewHeight = px2vp(size.height);
  704. if(this.isPhoneLan()){
  705. this.is_auto_hide_progress = false
  706. if(this.isHiCar()){
  707. return
  708. }
  709. setTimeout(() => {
  710. this.is_auto_hide_progress = true
  711. }, 6000)
  712. }else{
  713. this.startAutoHide()
  714. }
  715. });
  716. this.eventHub.on('onStateChange', (fg: boolean) => {
  717. if (fg && this.curState === 'STARTED') {
  718. this.stopPip();
  719. }
  720. });
  721. }
  722. //载入媒体库,艺术家,专辑等缓存
  723. initLoadCache(){
  724. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  725. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  726. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  727. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  728. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  729. if(ArrayUtil.isNotEmpty(cachedList)){
  730. this.mediaKuList = cachedList
  731. if(this.modeType==1){
  732. this.updateListData(this.mediaKuList)
  733. }
  734. }
  735. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  736. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  737. if(ArrayUtil.isNotEmpty(artistCachedList)){
  738. this.artistList = artistCachedList
  739. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  740. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  741. this.artistMap = new Map(parsedArray);
  742. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  743. if(this.modeType==2){
  744. this.updateListData(this.artistList)
  745. }
  746. }
  747. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  748. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  749. if(ArrayUtil.isNotEmpty(albumCachedList)){
  750. this.albumList = albumCachedList
  751. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  752. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  753. this.albumMap = new Map(parsedArray);
  754. if(this.modeType==3){
  755. this.updateListData(this.albumList)
  756. }
  757. }
  758. }
  759. startAutoHide() {
  760. if(this.isHiCar()){
  761. return
  762. }
  763. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  764. console.info('onecold startAutoHide')
  765. this.is_auto_hide_progress = false
  766. setTimeout(() => {
  767. this.is_auto_hide_progress = true
  768. }, 6000)
  769. }
  770. }
  771. applyThemeMode(mode: number) {
  772. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  773. if (mode === 1) {
  774. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  775. } else if (mode === 2) {
  776. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  777. }
  778. AppStorage.setOrCreate('currentColorMode', colorMode)
  779. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  780. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  781. AppStorage.setOrCreate('themeMode', mode)
  782. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  783. // 只有强制浅色/深色时才主动设置
  784. const context = getContext(this) as common.UIAbilityContext
  785. context.getApplicationContext().setColorMode(colorMode)
  786. }
  787. initSetting() {
  788. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  789. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  790. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  791. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  792. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  793. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  794. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  795. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  796. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  797. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  798. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  799. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  800. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  801. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  802. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  803. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  804. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  805. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  806. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  807. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  808. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  809. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  810. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  811. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  812. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  813. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  814. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  815. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  816. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  817. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  818. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  819. if(this.volumeSmall){
  820. this.volume = 0.5
  821. }else{
  822. this.volume = 1
  823. }
  824. //如果是hicar连接状态,这些都是false
  825. if(this.isHiCar()){
  826. this.isShowTitleBar = false//不显示导航栏
  827. this.columns=4
  828. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  829. {
  830. this.isShowHeader = false//二级菜单不显示头部
  831. this.isGridMusic= false//用list不用网格
  832. this.isCoverTopBig = false
  833. }
  834. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  835. }
  836. if (this.isSavePlayMode) {
  837. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  838. }
  839. if (this.isCustomizeBg) {
  840. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  841. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  842. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  843. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  844. } else {
  845. if (!this.isDarkMode) {
  846. this.titleBarModel.setTitleBarBackground(this.themeColor)
  847. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  848. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  849. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  850. } else {
  851. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  852. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  853. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  854. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  855. }
  856. }
  857. }
  858. doChangeSetting() {
  859. this.initSetting()
  860. this.deleteCache(this.currentPath)
  861. if (this.modeType === 0) {
  862. this.getSortedFiles(this.currentPath)
  863. }
  864. }
  865. doChangeBarHeight() {
  866. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  867. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  868. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  869. this.setBarHeightNormal()
  870. }
  871. }
  872. onPageShow() {
  873. this.knockController?.immersiveListening();
  874. app.setImageCacheCount(100);
  875. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  876. app.setImageRawDataCacheSize(104857600);
  877. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  878. }
  879. //开启线程查看各个数据库
  880. makeWorker() {
  881. setTimeout(() => {
  882. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  883. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  884. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  885. // workerInstance.postMessage({
  886. // code: 1,
  887. // data1: this.context,
  888. // data2: this.rootPath,
  889. // data3: this.lockPath,
  890. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  891. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  892. // });
  893. PreferencesUtil.putSync('isFirstApp', false)
  894. } else {
  895. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  896. workerInstance.postMessage({ code: 3, data: this.context });
  897. workerInstance.postMessage({ code: 4, data: this.context });
  898. this.getHistoryList(false)
  899. }
  900. }, 1000)
  901. workerInstance.onmessage = (e: MessageEvents): void => {
  902. switch (e.data.code) {
  903. case 101: //第一次扫描文件夹入库
  904. ToastUtil.showToast('刷新同步数据库成功!')
  905. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  906. this.doUpdateData()
  907. break;
  908. case 102: //查询媒体库列表
  909. this.isRefreshing = false
  910. this.mediaKuList = e.data.data
  911. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  912. Utility.doSortListAscending(this.mediaKuList)
  913. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  914. if (this.modeType === 1) {
  915. this.updateListData(this.mediaKuList)
  916. }
  917. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  918. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  919. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  920. // 只保存前100条记录到缓存中
  921. let truncatedList = this.mediaKuList.slice(0, 100);
  922. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  923. } else {
  924. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  925. }
  926. break;
  927. case 103: //收到查询艺术家列表
  928. this.isRefreshing = false
  929. this.artistMap = e.data.data1;
  930. this.artistList = e.data.data2;
  931. PreferencesUtil.putSync('artistCount', this.artistList.length)
  932. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  933. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  934. // 只保存前100条记录到缓存中
  935. let truncatedList = this.artistList.slice(0, 100);
  936. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  937. } else {
  938. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  939. }
  940. // 处理并缓存前60条艺术家数据
  941. const sortedEntries = Array.from(this.artistMap.entries())
  942. .sort((a, b) => b[1].length - a[1].length)
  943. .slice(0, 60);
  944. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  945. break;
  946. case 104: //收到查询专辑列表
  947. this.isRefreshing = false
  948. this.albumMap = e.data.data1;
  949. this.albumList = e.data.data2
  950. //查询完毕在启动是否自动播放
  951. if (this.isStartAutoPlay&&this.isCanAuto) {
  952. this.isCanAuto = false
  953. console.info('onecold startPlayOrResumePlay 757')
  954. this.startPlayOrResumePlay()
  955. }
  956. PreferencesUtil.putSync('albumCount', this.albumList.length)
  957. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  958. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  959. // 只保存前100条记录到缓存中
  960. let truncatedList = this.albumList.slice(0, 100);
  961. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  962. } else {
  963. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  964. }
  965. const mapArrayAlbum = Array.from(this.albumMap.entries())
  966. .sort((a, b) => b[1].length - a[1].length)
  967. .slice(0, 60);
  968. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  969. break;
  970. }
  971. };
  972. // 在调用terminate后,执行onexit
  973. workerInstance.onexit = (code) => {
  974. console.log("main thread terminate");
  975. }
  976. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  977. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  978. workerInstance.onerror = (err: ErrorEvent) => {
  979. console.log("onerror" + err.message);
  980. }
  981. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  982. //碰一碰分享的监听
  983. this.knockController = KnockController.getInstance(this.context);
  984. this.knockController?.immersiveListening();
  985. }
  986. onPageHide(): void {
  987. this.knockController?.immersiveDisableListening();
  988. }
  989. @State isFirstStartPlay: boolean = false
  990. //获取download_path
  991. async mkDownLoadDir() {
  992. const documentViewPicker = new picker.DocumentViewPicker()
  993. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  994. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  995. this.currentPath = this.rootPath
  996. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  997. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  998. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  999. Logger.info('onecold rootPath = ' + this.rootPath)
  1000. Logger.info('onecold lockPath = ' + this.lockPath)
  1001. if (!FileUtil.accessSync(this.lockPath)) {
  1002. FileUtil.mkdirSync(this.lockPath)
  1003. }
  1004. if (!FileUtil.accessSync(this.favPath)) {
  1005. FileUtil.mkdirSync(this.favPath)
  1006. }
  1007. if (!FileUtil.accessSync(this.historyPath)) {
  1008. FileUtil.mkdirSync(this.historyPath)
  1009. }
  1010. this.getSortedFiles(this.rootPath).then(() => {
  1011. this.isFavMusic = false
  1012. //穿山甲
  1013. // this.loadBannerAd(CSJUtil.getBannerID())
  1014. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1015. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1016. if (ArrayUtil.isEmpty(this.songList)) {
  1017. this.songList = this.getCurFileList()
  1018. } else {
  1019. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1020. }
  1021. if (ArrayUtil.isNotEmpty(this.songList)) {
  1022. this.isFirstStartPlay = true
  1023. this.sonDataSource.pushArrayData(this.songList)
  1024. if (this.currentSong === undefined) {
  1025. this.isFirstStartPlay = false
  1026. this.currentSong = this.songList[0]
  1027. }
  1028. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  1029. this.name = this.currentSong.name
  1030. this.cover = this.currentSong.pixelMapPath
  1031. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1032. } else {
  1033. this.name = '空空如也'
  1034. }
  1035. })
  1036. this.getFavList(false)
  1037. }
  1038. getFavList(isFavRefresh: boolean) {
  1039. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1040. this.favList = result
  1041. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1042. this.videoLocalList = this.favList
  1043. this.updateListData(this.videoLocalList)
  1044. }
  1045. })
  1046. }
  1047. getHistoryList(isRefresh: boolean) {
  1048. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1049. this.historyList = result
  1050. // for (let i = 0; i < this.historyList.length; i++) {
  1051. //
  1052. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1053. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1054. // }
  1055. if (isRefresh) {
  1056. this.videoLocalList = this.historyList
  1057. this.updateListData(this.videoLocalList, true)
  1058. }
  1059. })
  1060. }
  1061. // 组件消失生命周期
  1062. aboutToDisappear() {
  1063. console.info('LifeCycleComponent aboutToDisappear');
  1064. this.knockController?.immersiveDisableListening();
  1065. this.curIndex = 0
  1066. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1067. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1068. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1069. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1070. this.mDestroyPage = true;
  1071. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1072. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1073. this.stop();
  1074. }
  1075. this.mIjkMediaPlayer.off('audioInterrupt');
  1076. if (workerInstance) {
  1077. workerInstance.terminate();
  1078. }
  1079. this.stopPip();
  1080. this.destroyPipController()
  1081. }
  1082. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  1083. this.isFavMusic = false
  1084. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1085. if (isWorkerPost) {
  1086. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1087. }
  1088. if (this.modeType !== 0) {
  1089. this.openMusic(isOpen, destPath)
  1090. return
  1091. }
  1092. console.info('onecold getSortedFiles 2')
  1093. this.isCanBack = false
  1094. this.currentPath = curPath
  1095. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1096. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  1097. if (curPath === this.rootPath) {
  1098. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1099. } else {
  1100. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1101. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1102. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  1103. }
  1104. }
  1105. // Get the current file list and calculate its hash
  1106. this.fileList = FileUtil.listFileSync(curPath);
  1107. const currentHash = simpleHash(this.fileList);
  1108. // Check cache
  1109. const cachedValue = this.findCache(curPath);
  1110. Logger.info('onecold cachedValue = ' + cachedValue)
  1111. const cachedHash = this.findStringCache(curPath + '_hash');
  1112. const cachedDirList = this.findCache(curPath + "_dirList");
  1113. if (cachedValue !== undefined) {
  1114. // this.videoLocalList = cachedValue;
  1115. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1116. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1117. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1118. }
  1119. this.updateListData(cachedValue)
  1120. }
  1121. if (cachedDirList !== undefined) {
  1122. this.dirList = cachedDirList
  1123. }
  1124. //通过当前hash值和缓存hash判断list有没有变化
  1125. if (cachedValue && cachedHash === currentHash) {
  1126. return;
  1127. }
  1128. this.fileList = FileUtil.listFileSync(curPath)
  1129. let directories: Array<VideoItem> = [];
  1130. let files: Array<VideoItem> = [];
  1131. for (let i = 0; i < this.fileList.length; i++) {
  1132. console.info(`The name of file: ${this.fileList[i]}`);
  1133. let path = curPath + '/' + this.fileList[i]
  1134. if (FileUtil.isDirectory(path)) {
  1135. let item: VideoItem =
  1136. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1137. '')
  1138. if (this.isShowDir(item.name)) {
  1139. directories.push(item);
  1140. }
  1141. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1142. // Utility.doSortListAscending(directories)
  1143. } else {
  1144. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1145. let item: VideoItem =
  1146. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1147. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1148. files.push(item);
  1149. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1150. // this.doSortListAscending(files)
  1151. }
  1152. }
  1153. }
  1154. }
  1155. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1156. if (this.currentPath !== this.lockPath) {
  1157. files = result;
  1158. }
  1159. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1160. Utility.doSortListAscending(files)
  1161. if (this.currentPath === this.rootPath) {
  1162. this.dirList = directories
  1163. this.addCache(curPath + "_dirList", this.dirList);
  1164. }
  1165. //插入广告先注释掉
  1166. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1167. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1168. // directories.push(adItem)
  1169. // }
  1170. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1171. this.videoLocalList = directories.concat(files);
  1172. this.updateListData(this.videoLocalList)
  1173. if (ArrayUtil.isNotEmpty(files)) {
  1174. if (this.currentPath != this.rootPath) {
  1175. if (files) {
  1176. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1177. }
  1178. }
  1179. // 缓存结果
  1180. this.addCache(curPath, this.videoLocalList);
  1181. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1182. this.addStringCache(curPath + '_hash', currentHash);
  1183. }
  1184. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1185. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1186. //
  1187. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1188. //
  1189. // }
  1190. // this.setButtonStatus()
  1191. this.openMusic(isOpen, destPath)
  1192. });
  1193. }
  1194. //第三方app打开天天静听导入音乐后播放
  1195. openMusic(isOpen?: boolean, destPath?: string){
  1196. if (isOpen&&destPath) {
  1197. if (destPath === undefined) {
  1198. // 处理 destPath 为 undefined 的情况
  1199. return
  1200. }
  1201. if (destPath.endsWith('.lrc')) {
  1202. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1203. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1204. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1205. this.initLyric(lyricPath);
  1206. }
  1207. return
  1208. }
  1209. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  1210. this.doPlay(item2,0,false,true)
  1211. this.isShowPlay = true
  1212. }
  1213. }
  1214. //扫描文件夹入库
  1215. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1216. const files = FileUtil.listFileSync(curPath);
  1217. let mediaItems: VideoItem[] = [];
  1218. Logger.info('onecold scanDirectory start ')
  1219. for (const file of files) {
  1220. const fPath = `${curPath}/${file}`;
  1221. if (fPath === this.lockPath) {
  1222. Logger.info(`Skipping locked path: ${fPath}`);
  1223. continue;
  1224. }
  1225. if (FileUtil.isDirectory(fPath)) {
  1226. // Recursively scan subdirectories
  1227. const subDirItems = await this.scanDirectory(fPath);
  1228. mediaItems = mediaItems.concat(subDirItems);
  1229. } else {
  1230. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1231. // Process media files
  1232. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1233. let mediaItem: VideoItem =
  1234. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1235. mediaItems.push(mediaItem);
  1236. this.table.insert(mediaItem, (id: number) => {
  1237. });
  1238. }
  1239. }
  1240. }
  1241. return mediaItems;
  1242. }
  1243. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1244. animateTo({ duration: 666 }, () => {
  1245. this.opacityItem = 0;
  1246. });
  1247. setTimeout(() => {
  1248. this.videoLocalList = mList;
  1249. if (!noSort) {
  1250. if (this.modeType === 0 || this.modeType === 1) {
  1251. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1252. this.doSortType(this.sortType)
  1253. }
  1254. }
  1255. this.dataSource.pushArrayData(this.videoLocalList)
  1256. animateTo({ duration: 666 }, () => {
  1257. this.opacityItem = 1;
  1258. });
  1259. this.setButtonStatus()
  1260. }, 200);
  1261. }
  1262. //排序模式和多选模式
  1263. showPupDialog() {
  1264. if (this.modeType === 2 || this.modeType === 3) {
  1265. this.titleBarModel.setRightIcon(null)
  1266. } else {
  1267. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1268. }
  1269. let dataBean = new BubbleBean()
  1270. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1271. dataBean.color = this.themeColor
  1272. dataBean.modeType = this.modeType
  1273. dataBean.imageRes =
  1274. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1275. $r('app.media.refresh')]
  1276. let pup: XPopup;
  1277. if (this.isDarkMode) {
  1278. pup = XPopup.Builder()
  1279. .setPopupPosition(PopupPosition.BOTTOM)
  1280. .atView('pup_positon_music')
  1281. .setBackgroundColor(Color.Black)
  1282. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1283. .show()
  1284. } else {
  1285. pup = XPopup.Builder()
  1286. .setPopupPosition(PopupPosition.BOTTOM)
  1287. .atView('pup_positon_music')
  1288. .setBackgroundColor(Color.White)
  1289. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1290. .show()
  1291. }
  1292. dataBean.onItemClick = (i) => {
  1293. XPopup.dismissTop()
  1294. switch (i) {
  1295. case 0: //首页
  1296. this.modeType = 0
  1297. this.getSortedFiles(this.currentPath)
  1298. break
  1299. case 1:
  1300. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1301. this.modeType = 1
  1302. this.updateListData(this.mediaKuList)
  1303. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1304. break
  1305. case 2:
  1306. this.modeType = 2
  1307. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1308. this.updateListData(this.artistList)
  1309. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1310. break
  1311. case 3:
  1312. this.modeType = 3
  1313. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1314. this.updateListData(this.albumList)
  1315. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1316. break
  1317. case 4: //同步数据
  1318. // this.asyncCurrentPathData()
  1319. break
  1320. }
  1321. }
  1322. }
  1323. getCurFileList(): Array<VideoItem> {
  1324. if(this.isSearchMode){
  1325. return this.filteredList
  1326. }
  1327. let files: Array<VideoItem> = [];
  1328. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1329. for (let i = 0; i < this.videoLocalList.length; i++) {
  1330. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1331. files.push(this.videoLocalList[i]);
  1332. }
  1333. }
  1334. }
  1335. return files
  1336. }
  1337. setButtonStatus() {
  1338. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1339. this.isZero = false
  1340. } else {
  1341. this.isZero = true
  1342. }
  1343. if (this.currentPath !== this.rootPath &&
  1344. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1345. this.isHasDir = true //不为空,说明有子文件夹
  1346. } else {
  1347. this.isHasDir = false
  1348. }
  1349. }
  1350. showRankDialog() {
  1351. if ((this.modeType === 2&&!this.isCanBack) || (this.modeType === 3&&!this.isCanBack)) {
  1352. //动作面板
  1353. DialogHelper.showBottomSheetDialog({
  1354. title: "请选择排序模式",
  1355. maskColor: Color.Transparent,
  1356. // sheets: ["按名称升序", "按名称降序"],
  1357. sheets: [
  1358. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1359. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1360. { value: '按数量升序', fontColor: $r('app.color.text_color') },
  1361. { value: '按数量降序', fontColor: $r('app.color.text_color') },
  1362. ],
  1363. backgroundColor: $r('app.color.bg_card'),
  1364. height: '45%',
  1365. transition: AnimationHelper.transitionInDown(555),
  1366. onAction: (index) => {
  1367. switch (index) {
  1368. case 0:
  1369. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1370. break;
  1371. case 1:
  1372. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1373. break;
  1374. case 2:
  1375. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1376. // 1. Sort by type first
  1377. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1378. if (typeOrder !== 0) {
  1379. return typeOrder;
  1380. }
  1381. // 2. Then sort by artist count (numeric comparison)
  1382. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1383. if(this.modeType === 2){
  1384. sortMap = this.artistMap
  1385. }else{
  1386. sortMap = this.albumMap
  1387. }
  1388. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1389. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1390. return aArtistCount - bArtistCount;
  1391. });
  1392. break;
  1393. case 3:
  1394. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1395. // 1. Sort by type first
  1396. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1397. if (typeOrder !== 0) {
  1398. return typeOrder;
  1399. }
  1400. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1401. if(this.modeType === 2){
  1402. sortMap = this.artistMap
  1403. }else{
  1404. sortMap = this.albumMap
  1405. }
  1406. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1407. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1408. return bArtistCount - aArtistCount;
  1409. });
  1410. break;
  1411. }
  1412. this.updateListData(this.videoLocalList)
  1413. }
  1414. })
  1415. return
  1416. }
  1417. //动作面板
  1418. DialogHelper.showBottomSheetDialog({
  1419. title: "请选择排序模式",
  1420. maskColor: Color.Transparent,
  1421. height: '75%',
  1422. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1423. sheets: [
  1424. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1425. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1426. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1427. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1428. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1429. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1430. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1431. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1432. ],
  1433. backgroundColor: $r('app.color.bg_card'),
  1434. transition: AnimationHelper.transitionInDown(555),
  1435. onAction: (index) => {
  1436. this.doSortType(index)
  1437. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1438. this.updateListData(this.videoLocalList, true)
  1439. }
  1440. })
  1441. }
  1442. doSortType(index: number) {
  1443. switch (index) {
  1444. case 0:
  1445. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1446. // 类型排序优先级
  1447. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1448. if (typeOrder !== 0) {
  1449. return typeOrder;
  1450. }
  1451. // 处理艺术家可能为undefined的字符串比较
  1452. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1453. const artistB = b.artist?.trim() || '';
  1454. return artistA.localeCompare(artistB);
  1455. });
  1456. break;
  1457. case 1:
  1458. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1459. // 类型排序优先级
  1460. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1461. if (typeOrder !== 0) {
  1462. return typeOrder;
  1463. }
  1464. // 处理艺术家可能为undefined的字符串比较
  1465. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1466. const artistB = b.artist?.trim() || '';
  1467. return artistB.localeCompare(artistA);
  1468. });
  1469. break;
  1470. case 2:
  1471. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1472. // 类型排序优先级
  1473. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1474. if (typeOrder !== 0) {
  1475. return typeOrder;
  1476. }
  1477. // 处理专辑可能为undefined的字符串比较
  1478. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1479. const albumB = b.album?.trim() || '';
  1480. return albumA.localeCompare(albumB);
  1481. });
  1482. break;
  1483. case 3:
  1484. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1485. // 类型排序优先级
  1486. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1487. if (typeOrder !== 0) {
  1488. return typeOrder;
  1489. }
  1490. // 处理专辑可能为undefined的字符串比较
  1491. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1492. const albumB = b.album?.trim() || '';
  1493. return albumB.localeCompare(albumA);
  1494. });
  1495. break;
  1496. case 4:
  1497. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1498. break;
  1499. case 5:
  1500. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1501. break;
  1502. case 6:
  1503. this.videoLocalList.sort((a, b) => {
  1504. // First, sort by type
  1505. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1506. if (typeOrder !== 0) {
  1507. return typeOrder;
  1508. }
  1509. // If types are the same, sort by cTime in ascending order
  1510. return a.cTime.localeCompare(b.cTime);
  1511. });
  1512. break;
  1513. case 7:
  1514. this.videoLocalList.sort((a, b) => {
  1515. // First, sort by type
  1516. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1517. if (typeOrder !== 0) {
  1518. return typeOrder;
  1519. }
  1520. // If types are the same, sort by cTime in descending order
  1521. return b.cTime.localeCompare(a.cTime);
  1522. });
  1523. break;
  1524. }
  1525. }
  1526. showSheelDialog() {
  1527. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1528. // this.showTips()
  1529. // return
  1530. // }
  1531. this.showAddDialog()
  1532. }
  1533. showAddDialog() {
  1534. if (this.modeType === 2 || this.modeType === 3) {
  1535. return
  1536. }
  1537. DialogHelper.showActionSheetDialog({
  1538. title: "请选择添加方式(建议歌词文件一起导入)",
  1539. sheets: [
  1540. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  1541. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1542. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1543. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1544. ],
  1545. maskColor: Color.Transparent,
  1546. backgroundColor: $r('app.color.bg_card'),
  1547. transition: AnimationHelper.transitionInDown(555),
  1548. onAction: (index) => {
  1549. switch (index) {
  1550. case 0:
  1551. if (this.modeType === 0) {
  1552. this.showMkDialog()
  1553. } else {
  1554. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  1555. }
  1556. break;
  1557. case 1:
  1558. this.callFilePickerSelectFile()
  1559. break;
  1560. case 2:
  1561. this.showTips()
  1562. break;
  1563. case 3:
  1564. this.goSelectMusic()
  1565. break;
  1566. }
  1567. }
  1568. })
  1569. }
  1570. //拉起音频
  1571. goSelectMusic() {
  1572. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1573. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1574. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1575. ) {
  1576. ToastUtil.showToast('暂时不支持该设备')
  1577. return
  1578. }
  1579. try {
  1580. let documentSelectOptions = new picker.DocumentSelectOptions();
  1581. documentSelectOptions.authMode = true
  1582. documentSelectOptions.multiAuthMode = true
  1583. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1584. let documentPicker = new picker.DocumentViewPicker(this.context);
  1585. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1586. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1587. this.saveVideoDatas(documentSelectResult)
  1588. }
  1589. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1590. JSON.stringify(documentSelectResult));
  1591. }).catch((err: BusinessError) => {
  1592. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1593. });
  1594. } catch (error) {
  1595. let err: BusinessError = error as BusinessError;
  1596. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1597. }
  1598. }
  1599. async showTips() {
  1600. DialogHelper.showTipsDialog({
  1601. title: '使用提示:自动导入教程',
  1602. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1603. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1604. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1605. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1606. onAction: (action) => {
  1607. if (action == DialogAction.TWO) {
  1608. PreferencesUtil.putSync('isFirstMusic', false)
  1609. router.pushUrl({
  1610. url: 'pages/ScanFilePage'
  1611. });
  1612. }
  1613. }
  1614. })
  1615. }
  1616. showMkDialog() {
  1617. DialogHelper.showTextInputDialog({
  1618. title: '新建歌单',
  1619. maskColor: Color.Transparent,
  1620. text: '',
  1621. transition: AnimationHelper.transitionInDown(666),
  1622. onChange: (text) => {
  1623. console.error("onChange: " + text);
  1624. },
  1625. onAction: (action, dialogId, content) => {
  1626. // ToastUtil.showToast('content = ' +content)
  1627. if (action == DialogAction.TWO) {
  1628. const newName = content
  1629. const newPath = this.currentPath + '/' + newName
  1630. FileUtil.mkdir(newPath, true).then(() => {
  1631. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1632. this.getSortedFiles(this.currentPath)
  1633. }).catch((error: BusinessError) => {
  1634. console.error(error.message);
  1635. });
  1636. }
  1637. }
  1638. })
  1639. }
  1640. @State progress: number = 0;
  1641. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1642. if (ArrayUtil.isEmpty(uris)) {
  1643. return;
  1644. }
  1645. let newUris: string[] = [];
  1646. this.progress = 0
  1647. DialogHelper.showLoadingProgress({
  1648. progress: this.progress,
  1649. backCancel: false,
  1650. autoCancel: false,
  1651. loadColor: this.themeColor,
  1652. fontColor: this.themeColor
  1653. });
  1654. // 计算所有文件的总大小
  1655. let totalSize = 0;
  1656. for (let uri of uris) {
  1657. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1658. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1659. await fileIo.close(sourceFile.fd);
  1660. }
  1661. let totalRead = 0;
  1662. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1663. Logger.info(TAG, 'destPath uri: ' + destPath);
  1664. for (let i = 0; i < uris.length; i++) {
  1665. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1666. Logger.info(TAG, 'filePath uri: ' + filePath);
  1667. newUris.push(filePath);
  1668. try {
  1669. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1670. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1671. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1672. const buffer = new ArrayBuffer(buffSize);
  1673. let len = await fileIo.read(sourceFile.fd, buffer);
  1674. while (len > 0) {
  1675. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1676. totalRead += len;
  1677. // 计算总进度
  1678. this.progress = Math.floor((totalRead / totalSize) * 100);
  1679. DialogHelper.updateLoading('正在导入', this.progress);
  1680. len = await fileIo.read(sourceFile.fd, buffer);
  1681. }
  1682. await fileIo.close(sourceFile.fd);
  1683. await fileIo.close(destFile.fd);
  1684. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1685. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1686. let mediaItem: VideoItem =
  1687. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1688. this.table.insert(mediaItem, (id: number) => {
  1689. // 删除目标路径缓存
  1690. this.cache.delete(this.currentPath);
  1691. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1692. });
  1693. }
  1694. }
  1695. } catch (error) {
  1696. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1697. }
  1698. }
  1699. DialogHelper.closeLoading()
  1700. this.isZero = false
  1701. // setTimeout(() => {
  1702. // // 删除目标路径缓存
  1703. // this.cache.delete(this.currentPath);
  1704. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1705. // }, 500);
  1706. Logger.info(TAG, 'scan select video result:' + newUris)
  1707. }
  1708. //拉起音频
  1709. // goSelectMusic(){
  1710. //
  1711. // try {
  1712. // let audioSelectOptions = new picker.AudioSelectOptions();
  1713. // let audioPicker = new picker.AudioViewPicker(this.context);
  1714. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1715. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1716. // this.saveVideoDatas(audioSelectResult)
  1717. // }
  1718. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1719. // }).catch((err: BusinessError) => {
  1720. //
  1721. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1722. // });
  1723. // } catch (error) {
  1724. // let err: BusinessError = error as BusinessError;
  1725. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1726. // }
  1727. //
  1728. //
  1729. //
  1730. // }
  1731. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1732. if (!item) {
  1733. return undefined;
  1734. }
  1735. try {
  1736. let selectUris: Array<string> = [];
  1737. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1738. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1739. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1740. photoSelectOptions.maxSelectNumber = 1;
  1741. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1742. selectUris = photoSelectResult.photoUris;
  1743. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1744. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1745. console.info('file fd: ' + file.fd);
  1746. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1747. let imagePath = this.context.filesDir + FileUtil.separator + name
  1748. imagePath = fileUri.getUriFromPath(imagePath)
  1749. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1750. fileIo.copyFileSync(file.fd, file2.fd)
  1751. fileIo.closeSync(file);
  1752. fileIo.closeSync(file2);
  1753. if (item.filePath == this.currentSong?.filePath) {
  1754. this.cover = imagePath
  1755. }
  1756. if (item) {
  1757. item.pixelMapPath = imagePath
  1758. }
  1759. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1760. if (success) {
  1761. this.doUpdateData()
  1762. console.log("onecold 更新音乐封面成功,数据库已同步");
  1763. } else {
  1764. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1765. }
  1766. });
  1767. LogUtil.debug("onecold this.cover =" + this.cover)
  1768. return FileUtil.getFilePath(imagePath); // Return the image path here
  1769. } catch (err) {
  1770. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1771. return undefined;
  1772. }
  1773. }
  1774. // 拉起picker选择文件管理器
  1775. async callFilePickerSelectFile(): Promise<void> {
  1776. try {
  1777. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1778. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1779. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1780. } else {
  1781. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1782. }
  1783. let documentPicker = new picker.DocumentViewPicker();
  1784. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1785. Logger.info(TAG,
  1786. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1787. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1788. this.saveVideoDatas(DocumentSelectResult)
  1789. }
  1790. }).catch((err: BusinessError) => {
  1791. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1792. });
  1793. } catch (err) {
  1794. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1795. }
  1796. }
  1797. //重命名的对话框
  1798. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1799. DialogHelper.showTextInputDialog({
  1800. title: '重命名',
  1801. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1802. maskColor: Color.Transparent,
  1803. backgroundColor: Color.Grey,
  1804. transition: AnimationHelper.transitionInDown(666),
  1805. onChange: (text) => {
  1806. console.error("onChange: " + text);
  1807. },
  1808. onAction: (action, dialogId, content) => {
  1809. // ToastUtil.showToast('content = ' +content)
  1810. if (action == DialogAction.TWO) {
  1811. const newName = content
  1812. const newPath = this.currentPath + '/' + newName
  1813. console.log("onecold item = " + item.type);
  1814. this.doReName(index, newName, filePath, newPath, item)
  1815. }
  1816. }
  1817. })
  1818. }
  1819. //剪切 移动到另个文件夹的对话框
  1820. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1821. Logger.info('onecold showCutDialog')
  1822. let mList: Array<string> = []
  1823. let rPath = this.rootPath
  1824. if (isCurrent) {
  1825. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1826. rPath = this.currentPath
  1827. } else {
  1828. mList = Utility.getNameList(this.dirList);
  1829. rPath = this.rootPath
  1830. }
  1831. let dataBean = new BubbleBean()
  1832. dataBean.data = mList
  1833. dataBean.color = this.themeColor
  1834. dataBean.onItemClick = (i) => {
  1835. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1836. Logger.info('newPath = ' + newPath)
  1837. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1838. ToastUtil.showToast('移动成功')
  1839. this.table.deleteData(item, () => {
  1840. });
  1841. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1842. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1843. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1844. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1845. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1846. this.table.insert(newItem, (id: number) => {
  1847. //加入数据库
  1848. });
  1849. }
  1850. this.cache.delete(this.currentPath); // 删除原路径缓存
  1851. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1852. this.getSortedFiles(this.currentPath, true)
  1853. }).catch((error: BusinessError) => {
  1854. console.error(error.message);
  1855. });
  1856. XPopup.dismissTop()
  1857. }
  1858. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1859. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1860. popupPosition = PopupPosition.TOP
  1861. }
  1862. if (index <= 3) {
  1863. popupPosition = PopupPosition.BOTTOM
  1864. }
  1865. let pup: XPopup
  1866. if (this.isDarkMode) {
  1867. pup = XPopup.Builder()
  1868. .setPopupPosition(popupPosition)
  1869. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1870. .setBackgroundColor(Color.Black)
  1871. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1872. .show()
  1873. } else {
  1874. pup = XPopup.Builder()
  1875. .setPopupPosition(popupPosition)
  1876. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1877. .setBackgroundColor(Color.White)
  1878. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1879. .show()
  1880. }
  1881. }
  1882. //复制 到另个文件夹的对话框
  1883. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1884. Logger.info('onecoldv showCopyDialog')
  1885. let mList: Array<string> = []
  1886. let rPath = this.rootPath
  1887. if (isCurrent) {
  1888. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1889. rPath = this.currentPath
  1890. } else {
  1891. mList = Utility.getNameList(this.dirList);
  1892. rPath = this.rootPath
  1893. }
  1894. let dataBean = new BubbleBean()
  1895. dataBean.data = mList
  1896. dataBean.isCopy = true
  1897. dataBean.color = this.themeColor
  1898. dataBean.onItemClick = (i) => {
  1899. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1900. Logger.info('newPath = ' + newPath)
  1901. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1902. ToastUtil.showToast('复制成功')
  1903. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1904. this.getSortedFiles(this.currentPath)
  1905. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1906. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1907. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1908. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1909. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1910. this.table.insert(newItem, (id: number) => {
  1911. //加入数据库
  1912. });
  1913. }
  1914. }).catch((error: BusinessError) => {
  1915. console.error(error.message);
  1916. });
  1917. XPopup.dismissTop()
  1918. }
  1919. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1920. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1921. popupPosition = PopupPosition.TOP
  1922. }
  1923. if (index <= 3) {
  1924. popupPosition = PopupPosition.BOTTOM
  1925. }
  1926. let pup: XPopup
  1927. if (this.isDarkMode) {
  1928. pup = XPopup.Builder()
  1929. .setPopupPosition(popupPosition)
  1930. .atView(id)
  1931. .setMaxHeight('60%')
  1932. .setBackgroundColor(Color.Black)
  1933. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1934. .show();
  1935. } else {
  1936. pup = XPopup.Builder()
  1937. .setPopupPosition(popupPosition)
  1938. .atView(id)
  1939. .setMaxHeight('60%')
  1940. .setBackgroundColor(Color.White)
  1941. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1942. .show();
  1943. }
  1944. }
  1945. //重命名索引index的视频
  1946. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1947. FileUtil.rename(oldPath, newPath).then(async () => {
  1948. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1949. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1950. //如果是文件夹先删除源数据,再添加新数据
  1951. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1952. if (success) {
  1953. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1954. } else {
  1955. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1956. }
  1957. });
  1958. this.scanDirectory(newPath)
  1959. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1960. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1961. if (success) {
  1962. console.log(" onecold 重命名成功,数据库已同步");
  1963. } else {
  1964. console.error(" onecold 重命名数据库失败原因: " + error);
  1965. }
  1966. });
  1967. }
  1968. let mediaItem: VideoItem =
  1969. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1970. this.videoLocalList[index] = mediaItem;
  1971. }
  1972. this.cache.delete(this.currentPath)
  1973. this.getSortedFiles(this.currentPath, true)
  1974. }).catch((error: BusinessError) => {
  1975. console.error(error.message);
  1976. });
  1977. }
  1978. build() {
  1979. Scroll() {
  1980. Column() {
  1981. if (!this.isShowCoverHeader()) {
  1982. Column() {
  1983. Line().width('100%').height('100%')
  1984. }
  1985. .height(this.topRectHeight)
  1986. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1987. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1988. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1989. TitleBar({ model: $titleBarModel })
  1990. .id('pup_positon_music')
  1991. }
  1992. Stack() {
  1993. Column() {
  1994. XComponent({
  1995. id: 'xcomponentId',
  1996. type: 'surface',
  1997. libraryname: 'ijkplayer_napi',
  1998. controller: this.xcomponentController
  1999. })
  2000. .onLoad((event?: object) => {
  2001. if (!!event) {
  2002. this.initDelayPlay(event);
  2003. }
  2004. })
  2005. .onKeyEvent((event?: KeyEvent) => {
  2006. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2007. if (!event || event.type !== KeyType.Down) {
  2008. return;
  2009. }
  2010. //空格键 Space key controls pause/play
  2011. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  2012. console.info('onecold playOrPause 1999')
  2013. this.playOrPause()
  2014. }
  2015. // Right-click to fast forward
  2016. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2017. this.sessionFastForwardCallback(15);
  2018. }
  2019. // Left-click to rewind
  2020. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2021. this.sessionRewindCallback(15);
  2022. }
  2023. })
  2024. .onDestroy(() => {
  2025. })
  2026. .width('100%')// .width(this.videoWidth)
  2027. .aspectRatio(this.videoAspectRatio)
  2028. }
  2029. .aspectRatio(this.videoAspectRatio)
  2030. .justifyContent(FlexAlign.Center)
  2031. .backgroundColor(Color.Transparent)
  2032. .visibility(Visibility.Hidden)
  2033. .height(CommonConstants.FULL_PERCENT)
  2034. .width(CommonConstants.FULL_PERCENT)
  2035. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2036. height:this.isLandscape?'80%': '43%',
  2037. dragBar: true,
  2038. showClose: true,
  2039. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2040. blurStyle:BlurStyle.Thin,
  2041. backgroundColor:Color.Transparent,
  2042. title: { title: 'AB循环' }
  2043. })
  2044. Stack() {
  2045. Row() {
  2046. Blank()
  2047. .layoutWeight(1)
  2048. IndexerView(
  2049. {
  2050. indexArray: DEFAULT_INDEX,
  2051. selectedIndex: this.selectedIndex,
  2052. textSize: 12,
  2053. selectedColor: "#ff419ee5",
  2054. normalColor: "#ffa0a0a0",
  2055. floatSelectedTextColor: "#ffffff",
  2056. floatSelectedViewColor: "#ff419ee5",
  2057. onIndexChanged: (index) => {
  2058. this.listScroller.scrollToIndex(index)
  2059. }
  2060. })
  2061. .width(24)
  2062. .height("50%")
  2063. }.visibility(Visibility.None)
  2064. Column() {
  2065. if (!this.isShowCoverHeader()) {
  2066. this.tabTitle()
  2067. }
  2068. if(this.twoFingerType==4){
  2069. this.getWaterView()
  2070. }else{
  2071. if(this.isGridMusic){
  2072. this.getGridView()
  2073. }else {
  2074. this.getList()
  2075. }
  2076. }
  2077. if (this.modeType ==0||this.modeType==4) {
  2078. Column() {
  2079. emptyView(this.themeColor)
  2080. }
  2081. .position({ top:this.isShowCoverHeader() ? 260 : 180 })
  2082. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2083. .animation({ duration: 500 }),
  2084. TransitionEffect.scale({ x: 0, y: 0 })))
  2085. .justifyContent(FlexAlign.Center)
  2086. .opacity(this.isZero ? 1 : 0)
  2087. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2088. ? Visibility.Visible : Visibility.None)
  2089. .animation({
  2090. duration: 500,
  2091. curve: 'ease-in-out' // 可选动画曲线
  2092. })
  2093. .width('100%')
  2094. }
  2095. }
  2096. .layoutWeight(1)
  2097. .height('100%')
  2098. }
  2099. .layoutWeight(1)
  2100. .height('100%')
  2101. Row() {
  2102. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2103. .width(50)
  2104. .height(50)
  2105. .fontSize(13)
  2106. .margin({ top: 10, bottom: 10, right: 6 })
  2107. .backgroundColor(this.themeColor)
  2108. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2109. .onClick(() => {
  2110. if (this.isAllSelected) {
  2111. // 全不选
  2112. this.selectedFiles = [];
  2113. } else {
  2114. // 全选
  2115. this.selectedFiles = [...this.getCurFileList()];
  2116. }
  2117. this.isAllSelected = !this.isAllSelected;
  2118. })
  2119. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2120. .width(90)
  2121. .height(50)
  2122. .fontSize(13)
  2123. .margin({ top: 10, bottom: 10, right: 6 })
  2124. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2125. .backgroundColor(this.themeColor)
  2126. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2127. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2128. })
  2129. .onClick(() => {
  2130. this.isOneKeyTags = !this.isOneKeyTags
  2131. })
  2132. Button('乱码修复', { type: ButtonType.Capsule, stateEffect: true })
  2133. .width(90)
  2134. .height(50)
  2135. .fontSize(13)
  2136. .margin({ top: 10, bottom: 10, right: 6 })
  2137. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2138. .backgroundColor(this.themeColor)
  2139. .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2140. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2141. })
  2142. .onClick(() => {
  2143. this.isFixMessy = !this.isFixMessy
  2144. })
  2145. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2146. // .width('35%')
  2147. // .height(60)
  2148. // .id('music_cut')
  2149. // .margin({ top: 10, bottom: 10, right: 6 })
  2150. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2151. // .backgroundColor(this.themeColor)
  2152. // .onClick(() => {
  2153. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2154. // })
  2155. //
  2156. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2157. // .width('35%')
  2158. // .height(60)
  2159. // .id('music_cut_current')
  2160. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2161. // .margin({ top: 10, bottom: 10, right: 6 })
  2162. // .backgroundColor(this.themeColor)
  2163. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2164. // .onClick(() => {
  2165. //
  2166. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2167. // })
  2168. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2169. // .width('35%')
  2170. // .height(60)
  2171. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2172. // .margin({ top: 10, bottom: 10, right: 6 })
  2173. // .backgroundColor(this.themeColor)
  2174. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2175. // .onClick(() => {
  2176. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2177. // })
  2178. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2179. .width(50)
  2180. .height(50)
  2181. .fontSize(13)
  2182. .margin({ top: 10, bottom: 10, right: 6 })
  2183. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2184. .backgroundColor(this.themeColor)
  2185. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2186. .onClick(() => {
  2187. this.showWarnIsDelete()
  2188. })
  2189. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2190. .width(50)
  2191. .height(50)
  2192. .fontSize(13)
  2193. .margin({ top: 10, bottom: 10, right: 6 })
  2194. .backgroundColor(this.themeColor)
  2195. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2196. .onClick(() => {
  2197. this.selectedFiles = [];
  2198. this.isAllSelected = false
  2199. this.isMultiSelect = false
  2200. })
  2201. }
  2202. .width('100%')
  2203. .justifyContent(FlexAlign.Center)
  2204. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2205. .opacity(this.isMultiSelect ? 1 : 0)
  2206. .animation({
  2207. duration: 666,
  2208. curve: 'ease-in-out' // 可选动画曲线
  2209. })
  2210. .position(this.isShowCoverHeader() ? { bottom: 78 }
  2211. : { bottom: this.isPhoneLan() ? 130 : 170 }) // 将 Row 固定在底部
  2212. }
  2213. .width('100%')
  2214. .height('100%')
  2215. .alignContent(Alignment.Top)
  2216. Column() {
  2217. this.PlayController()
  2218. }
  2219. .hitTestBehavior(HitTestMode.Transparent)
  2220. .position({ bottom: 0 }) // 将 Row 固定在底部
  2221. .opacity(this.barBottomOpacity)
  2222. }
  2223. .width('100%')
  2224. .height('100%')
  2225. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2226. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2227. .backgroundImagePosition(Alignment.Center)
  2228. .backdropBlur(this.blurValue)
  2229. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2230. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2231. }
  2232. }
  2233. @Builder
  2234. TagsContentCoverBuilder() {
  2235. Scroll() {
  2236. Column() {
  2237. TagsContentCover(
  2238. {
  2239. selectedFiles:this.selectedFiles,
  2240. isOneKeyTags:this.isOneKeyTags,
  2241. onTagsResult:(result: boolean)=>{
  2242. this.isMultiSelect = false
  2243. if(result){//如果嵌入成功,更新数据
  2244. this.doUpdateData()
  2245. }
  2246. }
  2247. }
  2248. )
  2249. }
  2250. }
  2251. .width('100%')
  2252. .height('100%')
  2253. }
  2254. @Builder
  2255. FixMessyViewBuilder() {
  2256. Scroll() {
  2257. Column() {
  2258. FixMessyView(
  2259. {
  2260. selectedFiles:this.selectedFiles,
  2261. isFixMessy:this.isFixMessy,
  2262. onFixResult:(result: boolean)=>{
  2263. this.isMultiSelect = false
  2264. if(result){//如果嵌入成功,更新数据
  2265. this.doUpdateData()
  2266. }
  2267. }
  2268. }
  2269. )
  2270. }
  2271. }
  2272. .width('100%')
  2273. .height('100%')
  2274. }
  2275. asyncCurrentPathData() {
  2276. if (this.modeType == 0) {
  2277. workerInstance.postMessage({
  2278. code: 1,
  2279. data1: this.context,
  2280. data2: this.currentPath,
  2281. data3: this.lockPath,
  2282. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2283. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  2284. });
  2285. }
  2286. }
  2287. // 处理文件选择的函数
  2288. handleFileSelection(item: VideoItem, checked: boolean) {
  2289. if (checked) {
  2290. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2291. this.selectedFiles.push(item);
  2292. }
  2293. } else {
  2294. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2295. if (index > -1) {
  2296. this.selectedFiles.splice(index, 1);
  2297. }
  2298. }
  2299. }
  2300. private deleteComponentId: number = 0
  2301. //多选删除文件
  2302. showWarnIsDelete(){
  2303. this.getUIContext().getPromptAction().openCustomDialog({
  2304. builder: () => {
  2305. this.deleteComptentBuilder()
  2306. },
  2307. isModal:true,
  2308. showInSubWindow:false,
  2309. maskColor: Color.Transparent,
  2310. dialogTransition: // 设置弹窗内容显示的过渡效果
  2311. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  2312. .animation({ duration: 600, curve: Curve.Smooth }),
  2313. maskTransition: // 设置蒙层显示的过渡效果
  2314. TransitionEffect.opacity(0)
  2315. .animation({ duration: 600, curve: Curve.Smooth })
  2316. }).then((dialogId: number) => {
  2317. this.deleteComponentId = dialogId
  2318. })
  2319. .catch((error: BusinessError) => {
  2320. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  2321. })
  2322. }
  2323. @Builder
  2324. deleteComptentBuilder(){
  2325. DeleteComptent({
  2326. selectedFiles:this.selectedFiles,
  2327. onCancel:()=>{
  2328. this.isMultiSelect = false
  2329. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2330. },
  2331. onDeleteResult:(result: boolean)=>{
  2332. this.isMultiSelect = false
  2333. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2334. if(result){//如果删除成功,更新数据
  2335. this.selectedFiles = [];
  2336. this.isAllSelected = false
  2337. this.cache.delete(this.currentPath);
  2338. this.getSortedFiles(this.currentPath, true);
  2339. }
  2340. }
  2341. })
  2342. }
  2343. //多选移动文件
  2344. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2345. Logger.info('onecold showCutDialogForMultipleFiles')
  2346. let mList: Array<string> = []
  2347. let rPath = this.rootPath
  2348. if (isCurrent) {
  2349. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2350. rPath = this.currentPath
  2351. } else {
  2352. mList = Utility.getNameList(this.dirList);
  2353. rPath = this.rootPath
  2354. }
  2355. let dataBean = new BubbleBean();
  2356. dataBean.data = mList;
  2357. dataBean.color = this.themeColor
  2358. dataBean.onItemClick = (i) => {
  2359. const newDirPath = rPath + '/' + mList[i];
  2360. // Logger.info('newDirPath = ' + newDirPath)
  2361. this.selectedFiles.forEach((item) => {
  2362. const newPath = newDirPath + '/' + item.fileName;
  2363. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2364. ToastUtil.showToast('移动成功');
  2365. this.table.deleteData(item, () => {
  2366. this.cache.delete(this.currentPath); // 删除原路径缓存
  2367. this.cache.delete(newDirPath); // 删除目标路径缓存
  2368. this.getSortedFiles(this.currentPath, true);
  2369. });
  2370. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2371. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2372. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2373. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2374. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2375. this.table.insert(newItem, (id: number) => {
  2376. //加入数据库
  2377. });
  2378. }
  2379. }).catch((error: Error) => {
  2380. console.error(error.message);
  2381. });
  2382. });
  2383. this.isMultiSelect = false
  2384. this.selectedFiles = [];
  2385. this.isAllSelected = false
  2386. XPopup.dismissTop();
  2387. };
  2388. let pup: XPopup
  2389. if (this.isDarkMode) {
  2390. pup = XPopup.Builder()
  2391. .setPopupPosition(PopupPosition.TOP)
  2392. .atView(viewId)
  2393. .setBackgroundColor(Color.Black)
  2394. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2395. .show();
  2396. } else {
  2397. pup = XPopup.Builder()
  2398. .setPopupPosition(PopupPosition.TOP)
  2399. .atView(viewId)
  2400. .setBackgroundColor(Color.White)
  2401. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2402. .show();
  2403. }
  2404. }
  2405. /**
  2406. * 加载所有歌单
  2407. */
  2408. async loadAllPlaylists() {
  2409. try {
  2410. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  2411. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  2412. } catch (error) {
  2413. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  2414. }
  2415. }
  2416. /**
  2417. * 显示添加到歌单对话框
  2418. */
  2419. async showAddToPlaylistDialog(item: VideoItem) {
  2420. // 加载最新的歌单列表
  2421. await this.loadAllPlaylists()
  2422. showAddToPlaylistDialog(
  2423. item,
  2424. this.allPlaylists,
  2425. async (playlistId: string) => {
  2426. // 添加歌曲到歌单
  2427. const success = await this.playlistTable?.addSongToPlaylist(playlistId, item.filePath)
  2428. if (success) {
  2429. ToastUtil.showToast('已添加到歌单')
  2430. // 重新加载歌单列表
  2431. await this.loadAllPlaylists()
  2432. } else {
  2433. ToastUtil.showToast('歌曲已在该歌单中')
  2434. }
  2435. },
  2436. () => {
  2437. LogUtil.info('取消添加到歌单')
  2438. },
  2439. () => {
  2440. // 创建新歌单
  2441. showCreatePlaylistDialog(
  2442. async (name: string, description: string, coverPath?: string) => {
  2443. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  2444. if (success) {
  2445. ToastUtil.showToast('歌单创建成功')
  2446. // 重新加载歌单列表并打开添加对话框
  2447. await this.loadAllPlaylists()
  2448. await this.showAddToPlaylistDialog(item)
  2449. } else {
  2450. ToastUtil.showToast('歌单创建失败')
  2451. }
  2452. },
  2453. () => {
  2454. // 取消创建歌单
  2455. }
  2456. )
  2457. }
  2458. )
  2459. }
  2460. doFav(item: VideoItem) {
  2461. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2462. let isFav = 0
  2463. if (Utility.getIsFav(this.favList, item)) {
  2464. isFav = 0
  2465. } else {
  2466. isFav = 1
  2467. }
  2468. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2469. if (result) {
  2470. if (isFav === 1) {
  2471. ToastUtil.showToast('收藏成功');
  2472. } else {
  2473. ToastUtil.showToast('取消收藏成功');
  2474. }
  2475. this.deleteCache(this.currentPath)
  2476. this.getFavList(false)
  2477. if (this.modeType === 0 && !this.isFavMusic) {
  2478. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2479. this.getSortedFiles(this.currentPath)
  2480. }
  2481. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2482. workerInstance.postMessage({ code: 3, data: this.context });
  2483. workerInstance.postMessage({ code: 4, data: this.context });
  2484. }
  2485. })
  2486. }
  2487. //多选复制文件
  2488. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2489. console.log('onecold showCopyDialogForMultipleFiles');
  2490. let mList: Array<string> = []
  2491. let rPath = this.rootPath
  2492. if (isCurrent) {
  2493. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2494. rPath = this.currentPath
  2495. } else {
  2496. mList = Utility.getNameList(this.dirList);
  2497. rPath = this.rootPath
  2498. }
  2499. let dataBean = new BubbleBean();
  2500. dataBean.data = mList;
  2501. dataBean.isCopy = true
  2502. dataBean.color = this.themeColor
  2503. dataBean.onItemClick = (i) => {
  2504. const newDirPath = rPath + '/' + mList[i];
  2505. // Logger.info('newDirPath = ' + newDirPath)
  2506. this.selectedFiles.forEach((item) => {
  2507. const newPath = newDirPath + '/' + item.fileName;
  2508. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2509. ToastUtil.showToast('复制成功');
  2510. this.cache.delete(newDirPath); // 删除目标路径缓存
  2511. this.getSortedFiles(this.currentPath);
  2512. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2513. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2514. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2515. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2516. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2517. this.table.insert(newItem, (id: number) => {
  2518. //加入数据库
  2519. });
  2520. }
  2521. }).catch((error: Error) => {
  2522. console.error(error.message);
  2523. });
  2524. });
  2525. this.isMultiSelect = false
  2526. this.selectedFiles = [];
  2527. this.isAllSelected = false
  2528. XPopup.dismissTop();
  2529. };
  2530. let pup: XPopup
  2531. if (this.isDarkMode) {
  2532. pup = XPopup.Builder()
  2533. .setPopupPosition(PopupPosition.TOP)
  2534. .atView(viewId)
  2535. .setBackgroundColor(Color.Black)
  2536. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2537. .show();
  2538. } else {
  2539. pup = XPopup.Builder()
  2540. .setPopupPosition(PopupPosition.TOP)
  2541. .atView(viewId)
  2542. .setBackgroundColor(Color.White)
  2543. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2544. .show();
  2545. }
  2546. }
  2547. @Builder
  2548. private DirItem(item: VideoItem, index?: number) {
  2549. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2550. Row() {
  2551. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2552. $r('app.media.music_group'))
  2553. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2554. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2555. .fillColor(this.themeColor)// .fontSize(33)
  2556. .alt($r('app.media.music_group'))
  2557. .borderRadius('100%')
  2558. .clip(true)
  2559. .margin({ left: 20, top: 8, bottom: 8 })
  2560. Column() {
  2561. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2562. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2563. .maxLines(1)// .width('88%')
  2564. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2565. .animation({
  2566. duration: 555,
  2567. curve: 'ease-in-out',
  2568. })
  2569. .transition({
  2570. type: TransitionType.Insert,
  2571. opacity: 0,
  2572. translate: { x: 160 }
  2573. })
  2574. .margin({ left: 10, right: 20 })
  2575. .fontColor($r('app.color.text_color'))
  2576. Row() {
  2577. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2578. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2579. .padding({ top: 8 })
  2580. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2581. .fontColor($r('app.color.text_color'))
  2582. .margin({ left: 10 })
  2583. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2584. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2585. .padding({ top: 8 })
  2586. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2587. .fontColor($r('app.color.text_color'))
  2588. .margin({ left: 10 })
  2589. Blank()
  2590. }
  2591. }
  2592. .height('100%')
  2593. .layoutWeight(1)
  2594. .justifyContent(FlexAlign.Center)
  2595. .alignItems(HorizontalAlign.Start)
  2596. Blank()
  2597. Image($r('app.media.arrow_right'))
  2598. .height(25)
  2599. .margin({ right: 10 })
  2600. .alignSelf(ItemAlign.Center)
  2601. .id(item.filePath)
  2602. }
  2603. }
  2604. .backgroundColor(Color.Transparent)
  2605. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2606. .width('100%')
  2607. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2608. .opacity(this.opacityItem) // 绑定透明度
  2609. }
  2610. isShowDir(dirName: string) {
  2611. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2612. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2613. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2614. if (dirName === undefined) {
  2615. return true
  2616. }
  2617. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2618. return this.isShowSimi
  2619. }
  2620. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2621. return this.isShowFAV
  2622. }
  2623. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2624. return this.isShowHistory
  2625. }
  2626. return true
  2627. }
  2628. @State opacityItem: number = 1; // 控制透明度的状态变量
  2629. @Builder
  2630. private MusicItem(item: VideoItem, index?: number) {
  2631. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2632. Row() {
  2633. Stack() {
  2634. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2635. .fillColor(this.themeColor)
  2636. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2637. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2638. .alt($r('app.media.music_red'))
  2639. .borderRadius('100%')
  2640. .clip(true)
  2641. .draggable(false)
  2642. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2643. .autoResize(true) // 重采样,可减少内存占用
  2644. .opacity(this.opacityItem)// 绑定透明度
  2645. .margin({ left: 20 })
  2646. .gesture(LongPressGesture()
  2647. .onAction(async () => {
  2648. //如果是专辑和艺术家的首页,不能长按
  2649. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2650. return
  2651. //如果是我的收藏 最近播放等也不能长按
  2652. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2653. item.name === LocalMusic.STR_HISTORY_MUSIC
  2654. )
  2655. return
  2656. this.longItemFilePath = item.filePath
  2657. this.tempLyricContent = await this.getLyricContent(item)
  2658. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2659. })
  2660. .onActionEnd((event: GestureEvent) => {
  2661. }))
  2662. .onClick(()=>{
  2663. this.doPlay(item,index)
  2664. this.isShowPlay = true
  2665. })
  2666. }
  2667. Column() {
  2668. Column() {
  2669. Text(this.isShowFileName?item.fileName :item.name)
  2670. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2671. .maxLines(1)
  2672. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2673. .animation({
  2674. duration: 555,
  2675. curve: 'Linear',
  2676. })
  2677. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2678. $r('app.color.text_color'))
  2679. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2680. .padding({right:25})
  2681. .bindPopup(this.longItemFilePath === item.filePath, {
  2682. builder: this.MenuBuilder(item,index,item.filePath),
  2683. placement: Placement.Top,
  2684. // autoCancel: true,
  2685. mask: {color:'#33000000'},
  2686. // popupColor: Color.Yellow,
  2687. enableArrow: false,//是否显示箭头
  2688. showInSubWindow: false,
  2689. onStateChange: (e) => {
  2690. if (!e.isVisible) {
  2691. this.longItemFilePath = ''
  2692. this.tempLyricContent = ''
  2693. }
  2694. }
  2695. })
  2696. .gesture(LongPressGesture()
  2697. .onAction(async () => {
  2698. //如果是专辑和艺术家的首页,不能长按
  2699. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2700. return
  2701. //如果是我的收藏 最近播放等也不能长按
  2702. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2703. item.name === LocalMusic.STR_HISTORY_MUSIC
  2704. )
  2705. return
  2706. this.longItemFilePath = item.filePath
  2707. this.tempLyricContent = await this.getLyricContent(item)
  2708. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2709. })
  2710. .onActionEnd((event: GestureEvent) => {
  2711. })
  2712. )
  2713. Row() {
  2714. Column(){
  2715. Text(item.md5Str?.includes('Lossless')?
  2716. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2717. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2718. .padding({ top: 3,right:6,left:6,bottom:3 })
  2719. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2720. $r('app.color.text_color'))
  2721. .fontWeight(500)
  2722. .borderRadius(12)
  2723. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2724. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2725. .backgroundColor('#FFC107')
  2726. }
  2727. .padding({ top: 8 })
  2728. Text(StrUtil.isEmpty(item.artist) ? item.duration
  2729. :this.twoFingerType==2? item.artist +' ' + item.duration
  2730. : item.artist + ' ' + item?.duration)
  2731. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2732. .padding({ top: 8 ,right:25})
  2733. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  2734. .maxLines(1)
  2735. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2736. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2737. Color.Gray)
  2738. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2739. Blank()
  2740. Text(this.isShowFileName?item.duration:item.size)
  2741. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2742. .padding({ top: 8 })
  2743. .maxLines(1)
  2744. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  2745. ? Visibility.Visible : Visibility.None)
  2746. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2747. Color.Gray)
  2748. .margin({ left: 10 })
  2749. }
  2750. .gesture(LongPressGesture()
  2751. .onAction(async () => {
  2752. //如果是专辑和艺术家的首页,不能长按
  2753. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2754. return
  2755. //如果是我的收藏 最近播放等也不能长按
  2756. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2757. item.name === LocalMusic.STR_HISTORY_MUSIC
  2758. )
  2759. return
  2760. this.longItemFilePath = item.filePath
  2761. this.tempLyricContent = await this.getLyricContent(item)
  2762. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2763. })
  2764. .onActionEnd((event: GestureEvent) => {
  2765. })
  2766. )
  2767. }
  2768. .height('100%')
  2769. .width('100%')
  2770. .margin({ right: 10 })
  2771. .justifyContent(FlexAlign.Center)
  2772. .alignItems(HorizontalAlign.Start)
  2773. }
  2774. .height('100%')
  2775. .margin({ left: 5 })
  2776. .layoutWeight(1)
  2777. Column() {
  2778. Checkbox({ name: 'checkbox' + index })
  2779. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2780. .selectedColor(this.themeColor)
  2781. .shape(CheckBoxShape.CIRCLE)
  2782. .opacity(this.isMultiSelect ? 1 : 0)
  2783. .animation({
  2784. duration: 666,
  2785. curve: 'Smooth' // 可选动画曲线
  2786. })
  2787. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2788. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2789. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  2790. .width(22)
  2791. .height(22)
  2792. ImageAnimator()
  2793. .images(this.imagesF)// 动画数组
  2794. .duration(1000)// 持续
  2795. .state(this.animationState)// 动画状态
  2796. .fillMode(FillMode.Forwards)
  2797. .width(18)
  2798. .margin({ right: 20, top: 8, bottom: 8 })
  2799. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2800. Visibility.None)
  2801. .height(18)
  2802. .iterations(-1) // 播放次数
  2803. }
  2804. }
  2805. }
  2806. .backgroundColor(Color.Transparent)
  2807. .width('100%')
  2808. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2809. }
  2810. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2811. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  2812. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  2813. direction: Direction.Ltr,
  2814. buttonPadding:{top:12,bottom:12},
  2815. backgroundColor: Color.Transparent,
  2816. fontSize:14,
  2817. selectedFontSize:15,
  2818. selectedFontColor:Color.White,
  2819. selectedBackgroundColor: this.themeColor,
  2820. localizedTextPadding: {
  2821. end: LengthMetrics.vp(20),
  2822. start: LengthMetrics.vp(20)
  2823. }
  2824. })
  2825. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  2826. //当胶囊按钮的选择发生变化时调用此函数
  2827. capsuleSelectedIndexesChanged() {
  2828. this.modeType = this.tabSelectedIndexes[0]
  2829. }
  2830. @Builder
  2831. tabTitle() {
  2832. Column({ space: 2 }) {
  2833. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  2834. Line()
  2835. .width('100%')
  2836. .height(1)
  2837. .backgroundColor($r('app.color.index_background'))
  2838. .opacity(this.barOpacity)
  2839. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2840. }
  2841. .width('100%')
  2842. .height(this.topBarHeight)
  2843. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2844. }
  2845. // @Builder
  2846. // tabTitle() {
  2847. // Column() {
  2848. // // 使用 Stack 布局来实现绝对定位效果
  2849. // Stack() {
  2850. // // 背景动画容器
  2851. // Row() {
  2852. // ForEach(this.tabs, (i: string, index) => {
  2853. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2854. // Flex()
  2855. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2856. // .borderRadius(20)
  2857. // .padding(10)
  2858. // .margin(6)
  2859. // .width('100%')
  2860. // .height('100%')
  2861. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2862. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2863. // .opacity(this.modeType === index ? 1 : 0)
  2864. // .animation({
  2865. // duration: 666,
  2866. // playMode: PlayMode.Normal,
  2867. // curve: 'ease-in-out'
  2868. // });
  2869. // }
  2870. // .layoutWeight(1)
  2871. // .margin({
  2872. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2873. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2874. // });
  2875. // });
  2876. // }
  2877. // .width('100%')
  2878. // .height(50);
  2879. //
  2880. // // 导航栏容器
  2881. // Row() {
  2882. // ForEach(this.tabs, (item: string, index) => {
  2883. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2884. // Text(item)
  2885. // .fontSize(16)
  2886. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2887. // .padding(15)
  2888. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2889. // .onClick(() => {
  2890. // this.modeType = index;
  2891. // // this.onModeChange();
  2892. // });
  2893. // }
  2894. // .layoutWeight(1)
  2895. // .stateStyles({
  2896. // pressed: { opacity: 0.6 } // 按压反馈
  2897. // });
  2898. // });
  2899. // }
  2900. // .width('100%')
  2901. // .height(this.topBarHeight)
  2902. // .opacity(this.barOpacity)
  2903. // .backgroundColor(Color.Transparent);
  2904. //
  2905. // }
  2906. // .width('100%')
  2907. // .height(this.topBarHeight)
  2908. // .opacity(this.barOpacity)
  2909. //
  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. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2918. // }
  2919. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2920. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2921. isShowCoverHeader() {
  2922. if (!this.isShowHeader) {
  2923. return false
  2924. }
  2925. if (this.modeType == 0) {
  2926. if (this.isHistory || this.isFavMusic) {
  2927. return true
  2928. }
  2929. if (this.currentPath != this.rootPath) {
  2930. return true
  2931. }
  2932. }
  2933. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2934. }
  2935. @Builder
  2936. coverHeader() {
  2937. if (this.isShowCoverHeader()) {
  2938. Column() {
  2939. Stack() {
  2940. // 居中标题
  2941. Text('')
  2942. .fontSize(18)
  2943. .fontColor(Color.White)
  2944. .align(Alignment.Center)
  2945. // 左右按钮
  2946. Row() {
  2947. Image($r('app.media.left_back_white'))
  2948. .width(28)
  2949. .height(28)
  2950. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2951. .margin({ left: 12, right: 8 })
  2952. .onClick(() => {
  2953. animateTo({ duration: 555 }, () => {
  2954. this.doSwipBack()
  2955. })
  2956. })
  2957. Blank().flexGrow(1)
  2958. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2959. Image($r('app.media.add'))
  2960. .width(25)
  2961. .height(25)
  2962. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2963. .margin({ left: 8, right: 15 })
  2964. .onClick(() => {
  2965. this.showAddDialog()
  2966. })
  2967. }
  2968. }
  2969. .height(48)
  2970. .width('100%')
  2971. .alignItems(VerticalAlign.Center)
  2972. }
  2973. .height(48)
  2974. .width('100%')
  2975. Row() {
  2976. Column() {
  2977. Image(this.currentTitleCover)
  2978. .height(100)
  2979. .width(100)
  2980. .alt(this.imageLabel)
  2981. .borderRadius(8)
  2982. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2983. }
  2984. .alignItems(HorizontalAlign.Start)
  2985. .margin({ left: 30, top: 3, bottom: 15 })
  2986. Column() {
  2987. Column() {
  2988. Text(this.currentTitleName)
  2989. .fontSize(16)
  2990. .maxLines(1)
  2991. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2992. .fontWeight(FontWeight.Bold)
  2993. .fontColor($r('app.color.text_color'))
  2994. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2995. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2996. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2997. .fontSize(14)
  2998. .padding({ top: 8 })
  2999. .maxLines(1)
  3000. .fontWeight(FontWeight.Bold)
  3001. .fontColor($r('app.color.text_color'))
  3002. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3003. if(this.videoLocalList[0].genre){
  3004. Text(`风格:${this.videoLocalList[0].genre}`)
  3005. .fontSize(14)
  3006. .padding({ top: 8 })
  3007. .maxLines(1)
  3008. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  3009. this.videoLocalList[0].genre.includes(this.UNKONWN)
  3010. ?Visibility.None:Visibility.Visible)
  3011. .fontWeight(FontWeight.Bold)
  3012. .fontColor($r('app.color.text_color'))
  3013. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3014. }
  3015. if(this.videoLocalList[0].year){
  3016. Text(`发行时间:${this.videoLocalList[0].year}`)
  3017. .fontSize(14)
  3018. .padding({ top: 8 })
  3019. .maxLines(1)
  3020. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  3021. this.videoLocalList[0].year.includes(this.UNKONWN)
  3022. ?Visibility.None:Visibility.Visible)
  3023. .fontWeight(FontWeight.Bold)
  3024. .fontColor($r('app.color.text_color'))
  3025. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3026. }
  3027. }
  3028. if(this.modeType != 3){
  3029. Row() {
  3030. Text(`共${this.videoLocalList.length}首歌`)
  3031. .fontSize(13)
  3032. .fontWeight(FontWeight.Bold)
  3033. .padding({ top: 8 })
  3034. .fontColor($r('app.color.text_color'))
  3035. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3036. Blank()
  3037. }
  3038. }
  3039. }
  3040. .height('100%')
  3041. .width('100%')
  3042. .justifyContent(FlexAlign.Center)
  3043. .alignItems(HorizontalAlign.Start)
  3044. }
  3045. .height('100%')
  3046. .layoutWeight(1)
  3047. .margin({ left: 20 })
  3048. }
  3049. this.listViewTitle()
  3050. }
  3051. .backgroundImage(this.getCoverTitleBg())
  3052. .height(250)
  3053. .width('100%')
  3054. .backgroundImageSize({ height: '100%', width: '100%' })
  3055. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  3056. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  3057. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  3058. .justifyContent(FlexAlign.SpaceBetween)
  3059. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  3060. TransitionEffect.scale({ x: 0, y: 0 })))
  3061. } else {
  3062. this.listViewTitle()
  3063. }
  3064. }
  3065. getCoverTitleBg(): ResourceStr | image.PixelMap {
  3066. if (this.isCustomizeBg) {
  3067. return ('rgba(255,255,255,0.2)')
  3068. }
  3069. if (this.isDarkMode) {
  3070. return $r('app.color.user_center_card_background')
  3071. }
  3072. return this.currentTitleCover
  3073. }
  3074. @Builder
  3075. listViewTitle() {
  3076. Column() {
  3077. Row({ space: 8 }) {
  3078. Row({ space: 8 }) {
  3079. Image($r("app.media.hm_playlist"))
  3080. .width(25)
  3081. .margin({ left: 8 })
  3082. .fillColor(this.themeColor)
  3083. Text(this.artistList.length ==100 ? `共找到${this.artistCount}位艺术家`
  3084. :`共找到${this.artistList.length}位艺术家`)
  3085. .fontColor($r('app.color.text_color'))
  3086. .fontSize(14)
  3087. .opacity(this.opacityItem)
  3088. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3089. Text(this.albumList.length ==100 ? `共找到${this.albumCount+''}张专辑`
  3090. :`共找到${this.albumList.length}张专辑`)
  3091. .fontColor($r('app.color.text_color'))
  3092. .opacity(this.opacityItem)
  3093. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3094. .fontSize(14)
  3095. }
  3096. .layoutWeight(1)
  3097. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3098. Row() {
  3099. TextInput({
  3100. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  3101. text: this.searchText
  3102. })
  3103. .height(35)
  3104. .onChange((value: string) => {
  3105. this.onSearchInput(value);
  3106. })
  3107. .layoutWeight(1)
  3108. Text(`取消`)
  3109. .margin({ left: 10, right: 10 })
  3110. .fontColor($r('app.color.text_color'))
  3111. .fontSize(16)
  3112. .onClick(() => {
  3113. this.isSearchMode = false
  3114. this.searchText = ''
  3115. if (this.modeType === 2) {
  3116. this.updateListData(this.artistList)
  3117. } else {
  3118. this.updateListData(this.albumList)
  3119. }
  3120. })
  3121. }
  3122. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3123. .animation({
  3124. duration: 666,
  3125. curve: 'ease-in-out' // 可选动画曲线
  3126. })
  3127. Blank()
  3128. Image($r("app.media.search"))
  3129. .width(25)
  3130. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3131. .animation({
  3132. duration: 666,
  3133. curve: 'ease-in-out' // 可选动画曲线
  3134. })// .opacity(this.opacityItem)
  3135. .fillColor(this.themeColor)
  3136. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3137. .onClick(() => {
  3138. this.isSearchMode = true
  3139. })
  3140. Image($r("app.media.top_rank"))
  3141. .width(25)// .opacity(this.opacityItem)
  3142. .fillColor(this.themeColor)
  3143. .animation({
  3144. duration: 666,
  3145. curve: 'ease-in-out' // 可选动画曲线
  3146. })
  3147. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3148. .onClick(() => {
  3149. this.showRankDialog()
  3150. })
  3151. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3152. .width(25)
  3153. .animation({
  3154. duration: 666,
  3155. curve: 'ease-in-out' // 可选动画曲线
  3156. })
  3157. .fillColor(this.themeColor)
  3158. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3159. .onClick(() => {
  3160. this.isGridMusic = !this.isGridMusic
  3161. })
  3162. }
  3163. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  3164. Visibility.None)
  3165. .width('100%')
  3166. .padding(10)
  3167. .height(50)
  3168. .border({
  3169. width: { bottom: 1 },
  3170. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3171. })
  3172. Row({ space: 8 }) {
  3173. Row({ space: 8 }) {
  3174. Image($r("app.media.hm_play"))
  3175. .width(25)
  3176. .margin({ left: 8 })
  3177. .fillColor(this.themeColor)
  3178. Text(`播放全部`)
  3179. .fontColor($r('app.color.text_color'))
  3180. .fontSize(14)
  3181. .animation({
  3182. duration: 666,
  3183. curve: 'ease-in-out' // 可选动画曲线
  3184. })
  3185. if(Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length>0){
  3186. Text(this.modeType==1&&Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length==100?
  3187. `(${this.mediaKuCount}首)`
  3188. :`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  3189. .fontColor($r('app.color.text_color'))
  3190. .fontSize(14)
  3191. .opacity(this.opacityItem)
  3192. .animation({
  3193. duration: 666,
  3194. curve: 'ease-in-out' // 可选动画曲线
  3195. })
  3196. }
  3197. }
  3198. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3199. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3200. .animation({
  3201. duration: 666,
  3202. curve: 'ease-in-out' // 可选动画曲线
  3203. })
  3204. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  3205. .onTouch((event: TouchEvent) => {
  3206. if (event.type === TouchType.Down) {
  3207. this.isClickedPLayAll = true;
  3208. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  3209. this.isClickedPLayAll = false;
  3210. }
  3211. })
  3212. .onClick(() => {
  3213. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  3214. if (this.modeType === 0) {
  3215. const playList = this.getCurFileList();
  3216. const item = Utility.getPlayItem(playList, this.playType);
  3217. if (item) { // 显式检查undefined
  3218. this.doPlay(item);
  3219. }
  3220. } else {
  3221. const item = Utility.getPlayItem(this.mediaKuList, this.playType);
  3222. if (item) {
  3223. this.doPlay(item);
  3224. }
  3225. }
  3226. })
  3227. Row() {
  3228. TextInput({ placeholder: '输入名称...', text: this.searchText })
  3229. .height(35)
  3230. .onChange((value: string) => {
  3231. this.onSearchInput(value);
  3232. })
  3233. .layoutWeight(1)
  3234. Text(`取消`)
  3235. .margin({ left: 10, right: 10 })
  3236. .fontColor($r('app.color.text_color'))
  3237. .fontSize(16)
  3238. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3239. .onClick(() => {
  3240. this.isSearchMode = false
  3241. this.searchText = ''
  3242. if(this.modeType==0){
  3243. this.updateListData(this.videoLocalList)
  3244. } else if(this.modeType==1){
  3245. this.updateListData(this.mediaKuList)
  3246. } else if(this.modeType==2&&!this.isCanBack){
  3247. this.updateListData(this.artistList)
  3248. } else if(this.modeType==3&&!this.isCanBack){
  3249. this.updateListData(this.albumList)
  3250. }else if(this.modeType==4){
  3251. this.doSongListTask()
  3252. }
  3253. })
  3254. }
  3255. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3256. .animation({
  3257. duration: 666,
  3258. curve: 'ease-in-out' // 可选动画曲线
  3259. })
  3260. Blank()
  3261. Image($r("app.media.search"))
  3262. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  3263. .animation({
  3264. duration: 666,
  3265. curve: 'ease-in-out' // 可选动画曲线
  3266. })// .opacity(this.opacityItem)
  3267. .fillColor(this.themeColor)
  3268. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3269. .onClick(() => {
  3270. this.isSearchMode = true
  3271. })
  3272. Image($r("app.media.refresh"))
  3273. .fillColor(this.themeColor)
  3274. .width(25)
  3275. .visibility(this.modeType ==4||this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3276. .animation({
  3277. duration: 666,
  3278. curve: 'ease-in-out' // 可选动画曲线
  3279. })
  3280. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3281. .onClick(() => {
  3282. if (this.isFavMusic) {
  3283. this.getFavList(true)
  3284. } else {
  3285. if(this.modeType == 0){
  3286. this.asyncCurrentPathData()
  3287. }else if(this.modeType ==1){
  3288. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3289. }
  3290. }
  3291. })
  3292. Image($r("app.media.top_rank"))
  3293. .width(25)
  3294. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  3295. Visibility.Visible)// .opacity(this.opacityItem)
  3296. .animation({
  3297. duration: 666,
  3298. curve: 'ease-in-out' // 可选动画曲线
  3299. })
  3300. .fillColor(this.themeColor)
  3301. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3302. .onClick(() => {
  3303. this.showRankDialog()
  3304. })
  3305. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  3306. .width(24)
  3307. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3308. .animation({
  3309. duration: 666,
  3310. curve: 'ease-in-out' // 可选动画曲线
  3311. })
  3312. .fillColor(this.themeColor)
  3313. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3314. .onClick(() => {
  3315. this.isMultiSelect = !this.isMultiSelect
  3316. })
  3317. SymbolGlyph($r('sys.symbol.trash'))
  3318. .fontColor([this.themeColor])
  3319. .fontSize(25)
  3320. .effectStrategy(1)
  3321. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  3322. .animation({
  3323. duration: 666,
  3324. curve: 'ease-in-out' // 可选动画曲线
  3325. })
  3326. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3327. .onClick(() => {
  3328. this.clearVideoHistory() //清空播放记录
  3329. })
  3330. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3331. .width(24)
  3332. .animation({
  3333. duration: 666,
  3334. curve: 'ease-in-out' // 可选动画曲线
  3335. })
  3336. .fillColor(this.themeColor)
  3337. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3338. .bindPopup($$this.tipPopup, {
  3339. builder: this.popupBuilder,
  3340. placement: Placement.Bottom,
  3341. maskColor: 0x33000000,
  3342. enableArrow: true,
  3343. onStateChange: (e) => {
  3344. if (!e.isVisible) {
  3345. this.tipPopup = false;
  3346. }
  3347. }
  3348. })
  3349. .onClick(() => {
  3350. if(this.twoFingerType==4){
  3351. this.isGridMusic = false
  3352. this.twoFingerType=3
  3353. }else{
  3354. this.isGridMusic = !this.isGridMusic
  3355. }
  3356. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3357. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3358. })
  3359. }
  3360. .width('100%')
  3361. .padding(10)
  3362. .height(50)
  3363. .visibility(this.modeType === 0 || this.modeType === 1||this.modeType === 4
  3364. || this.isCanBack ? Visibility.Visible : Visibility.None)
  3365. .border({
  3366. width: { bottom: 1 },
  3367. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3368. })
  3369. }
  3370. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3371. }
  3372. // 第二步:popup构造器定义弹框内容
  3373. @Builder popupBuilder() {
  3374. Column({ space: 2 }) {
  3375. Text('友情提示:双指缩放可以放大缩小列表')
  3376. .fontSize(12)
  3377. .fontWeight(FontWeight.Regular)
  3378. .fontColor($r('app.color.text_color'))
  3379. }
  3380. .justifyContent(FlexAlign.SpaceAround)
  3381. .width(220)
  3382. .height(55)
  3383. .padding(15)
  3384. }
  3385. //搜索功能的实现
  3386. @State searchText: string = ''; // 用户输入内容
  3387. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3388. @State isSearchMode: boolean = false
  3389. // 实时搜索逻辑(带防抖)
  3390. private onSearchInput(value: string) {
  3391. this.searchText = value.trim();
  3392. let mSearchList: Array<VideoItem> = []
  3393. switch (this.modeType) {
  3394. case 0:
  3395. // mSearchList = this.videoLocalList
  3396. // break;
  3397. case 1:
  3398. mSearchList = this.mediaKuList
  3399. break;
  3400. case 2:
  3401. mSearchList = this.artistList
  3402. break;
  3403. case 3:
  3404. mSearchList = this.albumList
  3405. break;
  3406. }
  3407. // 新增条件判断:空输入时显示所有数据
  3408. if (this.searchText === '') {
  3409. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3410. } else {
  3411. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3412. //支持模糊匹配和艺术家 专辑匹配
  3413. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  3414. return regex.test(item.name.toLowerCase())||
  3415. regex.test(item.fileName?.toLowerCase() ?? "") ||
  3416. regex.test(item.artist?.toLowerCase() ?? "") ||
  3417. regex.test(item.album?.toLowerCase() ?? "")
  3418. });
  3419. }
  3420. this.updateListData(this.filteredList);
  3421. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3422. }
  3423. @State dragItem: number = -1
  3424. @State scaleItem: number = -1
  3425. @State neighborItem: number = -1
  3426. @State neighborScale: number = -1
  3427. @State offsetY: number = 0
  3428. private dragRefOffset: number = 0
  3429. private ITEM_INTV: number = 78
  3430. scaleSelect(item: number): number {
  3431. if (this.scaleItem === item) {
  3432. return 1.05
  3433. } else if (this.neighborItem === item) {
  3434. return this.neighborScale
  3435. } else {
  3436. return 1
  3437. }
  3438. }
  3439. itemMove(index: number, newIndex: number): void {
  3440. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3441. return;
  3442. }
  3443. let tmp = this.videoLocalList.splice(index, 1);
  3444. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3445. this.dataSource.pushArrayData(this.videoLocalList)
  3446. }
  3447. //瀑布流布局 支持双指缩放
  3448. @State columns: number = 2;
  3449. @State waterFlowScale: number = 1;
  3450. @State imageScale: number = 1;
  3451. @State waterFlowOpacity: number = 1;
  3452. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  3453. private columnChanged: boolean = false;
  3454. private oldColumn: number = this.columns;
  3455. private pinchTime: number = 0;
  3456. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  3457. changeColumns(scale: number) {
  3458. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3459. this.columns--;
  3460. this.columnChanged = true;
  3461. } else if (scale < 1 && this.columns < 4) {
  3462. this.columns++;
  3463. this.columnChanged = true;
  3464. }
  3465. }
  3466. @Builder
  3467. getWaterView(){
  3468. Scroll(this.scroller) {
  3469. Column() {
  3470. if(this.isShowCoverHeader()){
  3471. this.coverHeader()
  3472. }else {
  3473. this.listViewTitle()
  3474. }
  3475. WaterFlow({
  3476. scroller:this.waterScroller,
  3477. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  3478. }) {
  3479. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3480. FlowItem() {
  3481. this.MusicWaterCardItem(item,index)
  3482. }
  3483. .width('100%')
  3484. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3485. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3486. {
  3487. preview: MenuPreviewMode.IMAGE,
  3488. previewAnimationOptions: { scale: [0.8, 1.0] },
  3489. })
  3490. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3491. {
  3492. preview: MenuPreviewMode.IMAGE,
  3493. previewAnimationOptions: { scale: [0.8, 1.0] },
  3494. })
  3495. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  3496. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3497. TransitionEffect.scale({ x: 0, y: 0 })))
  3498. .gesture(
  3499. GestureGroup(GestureMode.Exclusive,
  3500. SwipeGesture({ direction: SwipeDirection.Horizontal })
  3501. .onAction((event: GestureEvent) => {
  3502. if (event) {
  3503. // this.sideBarController.openSideBar()
  3504. }
  3505. }),
  3506. TapGesture({ count: 1, fingers: 1 })
  3507. .onAction(async () => {
  3508. })
  3509. )
  3510. )
  3511. }, (item: VideoItem) => item.filePath)
  3512. }
  3513. // .columnsTemplate('repeat(auto-fit, 160)')
  3514. .id('waterflow') // 设置id用于截图
  3515. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  3516. .columnsGap(12) // 列间距
  3517. .rowsGap(16) // 行间距
  3518. .cachedCount(6)
  3519. // .margin(
  3520. // this.isHiCar()?{bottom:this.bottomBarHeight+90}:
  3521. // {bottom:this.isShowCoverHeader()? this.topBarHeight+35:
  3522. // this.isCoverOpacity()?this.topBarHeight+this.bottomBarHeight+78
  3523. // :this.topBarHeight+this.bottomBarHeight+108})
  3524. .margin({
  3525. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  3526. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  3527. })
  3528. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3529. .animation({ duration: 500, curve: Curve.Ease }))
  3530. .scrollBar(BarState.Off)
  3531. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  3532. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  3533. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  3534. .width('100%')
  3535. .height('100%')
  3536. .padding(10)
  3537. .opacity(this.waterFlowOpacity)
  3538. .scale({
  3539. x: this.waterFlowScale,
  3540. y: this.waterFlowScale,
  3541. centerX: 0,
  3542. centerY: 0
  3543. })
  3544. .onAppear(() => {
  3545. this.scroller.scrollEdge(Edge.Top)
  3546. })
  3547. .nestedScroll({
  3548. scrollForward: NestedScrollMode.PARENT_FIRST,
  3549. scrollBackward: NestedScrollMode.SELF_FIRST
  3550. })
  3551. .priorityGesture(
  3552. PinchGesture()
  3553. .onActionStart((event: GestureEvent) => {
  3554. // 双指捏合手势识别成功时截图
  3555. this.pinchTime = event.timestamp;
  3556. this.columnChanged = false;
  3557. this.oldColumn = this.columns;
  3558. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  3559. if (error) {
  3560. console.info('error:' + JSON.stringify(error));
  3561. return;
  3562. }
  3563. this.waterFlowSnapshot = pixmap;
  3564. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  3565. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  3566. if (this.oldColumn ===4) {
  3567. this.twoFingerType =3
  3568. this.isGridMusic = true
  3569. }else if (this.oldColumn ===1) {
  3570. this.twoFingerType =1
  3571. this.isGridMusic = false
  3572. }
  3573. return;
  3574. }
  3575. })
  3576. })
  3577. .onActionUpdate((event: GestureEvent) => {
  3578. // 手势更新:处理缩放逻辑和视觉效果
  3579. // 边界限制:防止超出列数范围时继续缩放
  3580. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  3581. return;
  3582. }
  3583. // 节流处理:避免过于频繁的更新,提升性能
  3584. if (event.timestamp - this.pinchTime < 10000000) {
  3585. return;
  3586. }
  3587. this.pinchTime = event.timestamp;
  3588. this.waterFlowScale = event.scale;
  3589. this.imageScale = event.scale;
  3590. // 根据缩放比例设置WaterFlow透明度
  3591. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  3592. this.waterFlowOpacity *= 3;
  3593. if (!this.columnChanged) {
  3594. this.changeColumns(event.scale);
  3595. }
  3596. // 列数改变后的缩放比例调整:避免出现空白区域
  3597. if (this.columnChanged) {
  3598. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  3599. // 限制缩放范围,确保视觉效果自然
  3600. if (event.scale < 1) {
  3601. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  3602. } else {
  3603. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  3604. }
  3605. }
  3606. })
  3607. .onActionEnd((event: GestureEvent) => {
  3608. // 手势结束:执行归位动画并保存状态
  3609. // 执行归位动画:平滑过渡到正常状态
  3610. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  3611. this.waterFlowScale = 1;
  3612. this.waterFlowOpacity = 1;
  3613. })
  3614. // 持久化保存当前列数:下次启动时恢复
  3615. PreferencesUtil.putSync('lastColumns', this.columns);
  3616. })
  3617. )
  3618. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3619. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3620. .onDrop((event?: DragEvent) => {
  3621. try {
  3622. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3623. if (dragData !== undefined) {
  3624. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3625. if (records.length > 0) {
  3626. for (let i = 0; i < records.length; i++) {
  3627. let types = records[i].getTypes();
  3628. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3629. const fileUriUds =
  3630. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3631. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3632. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3633. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3634. this.targetFile = fileUriUds.oriUri;
  3635. this.saveVideoDatas([this.targetFile])
  3636. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3637. }
  3638. }
  3639. }
  3640. } else {
  3641. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3642. }
  3643. } else {
  3644. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3645. }
  3646. } catch (error) {
  3647. const err = error as BusinessError;
  3648. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3649. }
  3650. })
  3651. }
  3652. }
  3653. .scrollBar(BarState.Off)
  3654. }
  3655. //瀑布流卡片布局
  3656. @Builder
  3657. private MusicWaterCardItem(item: VideoItem, index: number) {
  3658. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3659. Stack() {
  3660. Column() {
  3661. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3662. .backgroundImageSize(ImageSize.Auto)
  3663. .borderRadius({
  3664. topLeft: 12,
  3665. topRight : 12,
  3666. bottomLeft: 0,
  3667. bottomRight: 0
  3668. })
  3669. .draggable(false)// 禁止长按手势拖动
  3670. // .autoResize(true) // 重采样,可减少内存占用
  3671. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3672. .width('100%')
  3673. .height('auto')
  3674. .objectFit(ImageFit.Auto)
  3675. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3676. height: '99%' ,
  3677. dragBar: true,
  3678. onDisappear: () => {
  3679. this.longItemFilePath = '';
  3680. this.tempLyricContent = ''
  3681. },
  3682. showClose: true,
  3683. preferType: SheetType.CENTER ,
  3684. title: { title: '编辑标签' }
  3685. })
  3686. .draggable(false)
  3687. .opacity(this.opacityItem)// 绑定透明度
  3688. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3689. // .animation({ duration: 500, curve: Curve.Ease }))
  3690. .animation({
  3691. duration: 666,
  3692. curve: 'ease-in-out' // 可选动画曲线
  3693. })
  3694. .margin({
  3695. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3696. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3697. })
  3698. Column() {
  3699. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3700. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  3701. .maxLines(1)
  3702. .fontWeight(FontWeight.Bold)
  3703. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3704. .animation({
  3705. duration: 555,
  3706. curve: 'Linear',
  3707. })
  3708. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3709. height: '95%',
  3710. dragBar: true,
  3711. showClose: true,
  3712. onDisappear: () => {
  3713. this.longItemFilePathDetail = '';
  3714. },
  3715. blurStyle:BlurStyle.Thin,
  3716. backgroundColor:Color.Transparent,
  3717. preferType: SheetType.CENTER ,
  3718. title: { title: '详情' }
  3719. })
  3720. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3721. $r('app.color.text_color'))
  3722. Column() {
  3723. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3724. .fontSize(11)
  3725. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3726. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3727. .fontColor($r('app.color.text_color'))
  3728. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3729. .fontSize(11)
  3730. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3731. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3732. .fontColor($r('app.color.text_color'))
  3733. Row(){
  3734. Column(){
  3735. Text(item.md5Str?.includes('Lossless')?
  3736. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3737. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  3738. .padding({ top: 3,right:6,left:6,bottom:3 })
  3739. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3740. $r('app.color.text_color'))
  3741. .fontWeight(500)
  3742. .borderRadius(12)
  3743. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3744. .backgroundColor('#FFC107')
  3745. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  3746. }
  3747. .margin({ top: 2 ,right:6})
  3748. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3749. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3750. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3751. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  3752. .maxLines(1)
  3753. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3754. .margin({ top: 2})
  3755. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3756. || item.type == CommonConstants.TYPE_IS_ALBUM
  3757. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3758. .fontWeight(FontWeight.Medium)
  3759. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3760. $r('app.color.text_color'))
  3761. }
  3762. }
  3763. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3764. }
  3765. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  3766. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  3767. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  3768. .width('100%')
  3769. .justifyContent(FlexAlign.Center)
  3770. .margin({
  3771. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3772. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3773. })
  3774. }
  3775. .width('100%')
  3776. .borderRadius(12)
  3777. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3778. .backgroundImageSize({ height: '100%', width: '100%' })
  3779. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3780. .animation({ curve: Curve.Sharp, duration: 300 })
  3781. Checkbox({ name: 'checkbox' + index })
  3782. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3783. .selectedColor(this.themeColor)
  3784. .shape(CheckBoxShape.CIRCLE)
  3785. .opacity(this.isMultiSelect ? 1 : 0)
  3786. .animation({
  3787. duration: 666,
  3788. curve: 'Smooth' // 可选动画曲线
  3789. })
  3790. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3791. Visibility.None)
  3792. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3793. .margin({ left: 20, top: 8, bottom: 8 })
  3794. .width(38)
  3795. .height(38)
  3796. }
  3797. }
  3798. .backgroundColor(Color.Transparent)
  3799. .width('100%')
  3800. .height('auto')
  3801. .padding({top:2})
  3802. .reuseId('card_item')
  3803. .onClick(() => {
  3804. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3805. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3806. this.handleFileSelection(item, !isChecked);
  3807. } else {
  3808. this.doPlay(item, index)
  3809. }
  3810. })
  3811. }
  3812. // Grid布局的开始
  3813. private dragRefOffSetX: number = 0;
  3814. private dragRefOffSetY: number = 0;
  3815. private FIX_VP_X: number = 180;
  3816. private FIX_VP_Y: number = 84;
  3817. isDraggable(index: number): boolean {
  3818. return index >= 0;
  3819. }
  3820. getRowEnd(item: number) {
  3821. if (item.toString() === '0') {
  3822. return 1;
  3823. } else {
  3824. return 0;
  3825. }
  3826. }
  3827. isInLeft(index: number) {
  3828. return index % 2 == 0;
  3829. }
  3830. down(index: number): void {
  3831. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  3832. return;
  3833. }
  3834. this.offsetY -= this.FIX_VP_Y;
  3835. this.dragRefOffSetY += this.FIX_VP_Y;
  3836. this.itemMove(index, index + 1);
  3837. }
  3838. up(index: number): void {
  3839. if (!this.isDraggable(index - 2)) {
  3840. return;
  3841. }
  3842. this.offsetY += this.FIX_VP_Y;
  3843. this.dragRefOffSetY -= this.FIX_VP_Y;
  3844. this.itemMove(index, index - 1);
  3845. }
  3846. left(index: number): void {
  3847. if (this.isInLeft(index)) {
  3848. return;
  3849. }
  3850. if (!this.isDraggable(index - 1)) {
  3851. return;
  3852. }
  3853. this.offsetX += this.FIX_VP_X;
  3854. this.dragRefOffSetX -= this.FIX_VP_X;
  3855. this.itemMove(index, index - 1)
  3856. }
  3857. right(index: number): void {
  3858. if (!this.isInLeft(index)) {
  3859. return;
  3860. }
  3861. if (!this.isDraggable(index + 1)) {
  3862. return;
  3863. }
  3864. this.offsetX -= this.FIX_VP_X;
  3865. this.dragRefOffSetX += this.FIX_VP_X;
  3866. this.itemMove(index, index + 1)
  3867. }
  3868. private scroller: Scroller = new Scroller();
  3869. private waterScroller: Scroller = new Scroller();
  3870. @State startIndex: number = 0
  3871. @State endIndex: number = 0
  3872. @State scaleValue: number = 1
  3873. @State pinchValue: number = 1
  3874. layoutOptionsForHeader: GridLayoutOptions = {
  3875. regularSize: [1, 1], // 只支持[1, 1]
  3876. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3877. };
  3878. @Builder
  3879. getGridView() {
  3880. Grid(this.scroller, this.layoutOptionsForHeader) {
  3881. GridItem() {
  3882. if (this.isShowCoverHeader()) {
  3883. this.coverHeader()
  3884. } else {
  3885. this.listViewTitle()
  3886. }
  3887. }
  3888. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3889. GridItem() {
  3890. Stack({ alignContent: Alignment.Center }) {
  3891. this.MusicItemGrid(item, index)
  3892. }
  3893. }
  3894. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3895. {
  3896. preview: MenuPreviewMode.IMAGE,
  3897. previewAnimationOptions: { scale: [0.8, 1.0] },
  3898. })
  3899. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3900. {
  3901. preview: MenuPreviewMode.IMAGE,
  3902. previewAnimationOptions: { scale: [0.8, 1.0] },
  3903. })
  3904. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3905. TransitionEffect.scale({ x: 0, y: 0 })))
  3906. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3907. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3908. .zIndex(this.dragItem === index ? 1 : 0)
  3909. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3910. }, (item: VideoItem) => item.filePath)
  3911. }
  3912. .width(this.isShowHeader ? '100%' : '94%')
  3913. .height('100%')
  3914. .editMode(true)
  3915. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3916. .animation({ duration: 500, curve: Curve.Ease }))
  3917. .margin(
  3918. this.isHiCar()?{bottom:this.bottomBarHeight+98}:
  3919. {
  3920. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3921. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3922. })
  3923. .reuseId('grid_item')
  3924. .layoutWeight(1)
  3925. .scrollBar(BarState.Off)
  3926. .supportAnimation(true)
  3927. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3928. .columnsTemplate(
  3929. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3930. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3931. )
  3932. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3933. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3934. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3935. .gesture(PinchGesture({ fingers: 2 })
  3936. .onActionEnd((event: GestureEvent) => {
  3937. this.setGridTwoFingers()
  3938. })
  3939. .onActionUpdate(e => {
  3940. this.scaleValue = this.pinchValue * e.scale
  3941. })
  3942. .onActionStart(e => {
  3943. }))
  3944. .enableScrollInteraction(true)
  3945. .onScrollIndex((start: number, end: number) => {
  3946. this.startIndex = start
  3947. this.endIndex = end
  3948. })
  3949. .onScrollFrameBegin((offset: number) => {
  3950. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3951. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3952. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3953. if (this.isScrollHide) {
  3954. this.setBarHeightHide2(offset)
  3955. } else {
  3956. this.setBarHeightNormal()
  3957. }
  3958. } else {
  3959. this.setBarHeightHide(offset)
  3960. }
  3961. return { offsetRemain: offset };
  3962. })
  3963. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3964. .onDrop((event?: DragEvent) => {
  3965. try {
  3966. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3967. if (dragData !== undefined) {
  3968. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3969. if (records.length > 0) {
  3970. for (let i = 0; i < records.length; i++) {
  3971. let types = records[i].getTypes();
  3972. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3973. const fileUriUds =
  3974. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3975. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3976. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3977. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3978. this.targetFile = fileUriUds.oriUri;
  3979. this.saveVideoDatas([this.targetFile])
  3980. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3981. }
  3982. }
  3983. }
  3984. } else {
  3985. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3986. }
  3987. } else {
  3988. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3989. }
  3990. } catch (error) {
  3991. const err = error as BusinessError;
  3992. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3993. }
  3994. })
  3995. }
  3996. @State targetFile: string = '';
  3997. setGridTwoFingers() {
  3998. this.pinchValue = this.scaleValue;
  3999. Logger.info('this.pinchValue = ' + this.pinchValue);
  4000. if (this.pinchValue >= 1) {
  4001. this.twoFingerType++
  4002. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4003. if(this.twoFingerType >= 4){
  4004. this.twoFingerType = 4//切换成瀑布流
  4005. this.columns = 4
  4006. }
  4007. } else {
  4008. this.twoFingerType--
  4009. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4010. if (this.twoFingerType < 1) {
  4011. this.twoFingerType = 3
  4012. this.isGridMusic = false
  4013. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4014. }
  4015. }
  4016. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4017. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4018. this.pinchValue = 1;
  4019. this.scaleValue = 1;
  4020. }
  4021. @State longItemFilePath: string = ''
  4022. @State tempLyricContent: string = ''
  4023. @Builder
  4024. private MusicItemGrid(item: VideoItem, index: number) {
  4025. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4026. Stack() {
  4027. Column() {
  4028. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  4029. .height(this.getGridHeight())
  4030. .width(this.getGridWight())
  4031. .draggable(false)
  4032. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4033. .autoResize(true) // 重采样,可减少内存占用
  4034. .alt($r('app.media.ic_avatar2'))
  4035. .clip(true)
  4036. .borderRadius({
  4037. topLeft: 12,
  4038. topRight: 12,
  4039. bottomLeft: 0,
  4040. bottomRight: 0
  4041. })
  4042. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4043. height: '99%' ,
  4044. dragBar: true,
  4045. onDisappear: () => {
  4046. this.longItemFilePath = '';
  4047. this.tempLyricContent = ''
  4048. },
  4049. showClose: true,
  4050. preferType: SheetType.CENTER ,
  4051. title: { title: '编辑标签' }
  4052. })
  4053. .draggable(false)
  4054. .opacity(this.opacityItem)// 绑定透明度
  4055. .animation({
  4056. duration: 666,
  4057. curve: 'ease-in-out' // 可选动画曲线
  4058. })
  4059. .margin({
  4060. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4061. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4062. })
  4063. Column() {
  4064. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4065. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4066. .maxLines(1)
  4067. .fontWeight(FontWeight.Bold)
  4068. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4069. .animation({
  4070. duration: 555,
  4071. curve: 'Linear',
  4072. })
  4073. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4074. height: '95%',
  4075. dragBar: true,
  4076. showClose: true,
  4077. onDisappear: () => {
  4078. this.longItemFilePathDetail = '';
  4079. },
  4080. blurStyle:BlurStyle.Thin,
  4081. backgroundColor:Color.Transparent,
  4082. preferType: SheetType.CENTER ,
  4083. title: { title: '详情' }
  4084. })
  4085. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4086. $r('app.color.text_color'))
  4087. Column() {
  4088. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4089. .fontSize(11)
  4090. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4091. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4092. .fontColor($r('app.color.text_color'))
  4093. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4094. .fontSize(11)
  4095. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4096. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4097. .fontColor($r('app.color.text_color'))
  4098. Row(){
  4099. Column(){
  4100. Text(item.md5Str?.includes('Lossless')?
  4101. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4102. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4103. .padding({ top: 3,right:6,left:6,bottom:3 })
  4104. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4105. $r('app.color.text_color'))
  4106. .fontWeight(500)
  4107. .borderRadius(12)
  4108. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4109. .backgroundColor('#FFC107')
  4110. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4111. }
  4112. .margin({ top: 2 ,right:6})
  4113. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4114. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4115. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4116. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  4117. .maxLines(1)
  4118. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4119. .margin({ top: 2})
  4120. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4121. || item.type == CommonConstants.TYPE_IS_ALBUM
  4122. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4123. .fontWeight(FontWeight.Medium)
  4124. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4125. $r('app.color.text_color'))
  4126. }
  4127. }
  4128. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4129. }
  4130. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  4131. .width(this.getGridWight())
  4132. .justifyContent(FlexAlign.Center)
  4133. .margin({
  4134. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4135. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4136. })
  4137. }
  4138. .width(this.getGridWight())
  4139. .borderRadius(12)
  4140. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  4141. .backgroundImageSize({ height: '100%', width: '100%' })
  4142. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4143. .animation({ curve: Curve.Sharp, duration: 300 })
  4144. Checkbox({ name: 'checkbox' + index })
  4145. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4146. .selectedColor(this.themeColor)
  4147. .shape(CheckBoxShape.CIRCLE)
  4148. .opacity(this.isMultiSelect ? 1 : 0)
  4149. .animation({
  4150. duration: 666,
  4151. curve: 'Smooth' // 可选动画曲线
  4152. })
  4153. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4154. Visibility.None)
  4155. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4156. .margin({ left: 20, top: 8, bottom: 8 })
  4157. .width(38)
  4158. .height(38)
  4159. }
  4160. }
  4161. .backgroundColor(Color.Transparent)
  4162. .width('100%')
  4163. .padding({ top: 15 })
  4164. .height(this.getGridAllHeight())
  4165. .onClick(() => {
  4166. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4167. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4168. this.handleFileSelection(item, !isChecked);
  4169. } else {
  4170. this.doPlay(item, index)
  4171. }
  4172. })
  4173. }
  4174. getGridAllHeight() {
  4175. let heightG = 222
  4176. switch (this.twoFingerType) {
  4177. case 1:
  4178. heightG = 143
  4179. break;
  4180. case 2:
  4181. heightG = 178
  4182. break;
  4183. case 3:
  4184. heightG = 222
  4185. break;
  4186. }
  4187. return heightG
  4188. }
  4189. getGridHeight() {
  4190. let heightG = 150
  4191. switch (this.twoFingerType) {
  4192. case 1:
  4193. heightG = 80
  4194. break;
  4195. case 2:
  4196. heightG = 110
  4197. break;
  4198. case 3:
  4199. heightG = 150
  4200. break;
  4201. }
  4202. return heightG
  4203. }
  4204. getGridWight() {
  4205. let wightG = 158
  4206. switch (this.twoFingerType) {
  4207. case 1:
  4208. wightG = 80
  4209. break;
  4210. case 2:
  4211. wightG = 110
  4212. break;
  4213. case 3:
  4214. wightG = 158
  4215. break;
  4216. }
  4217. return wightG
  4218. }
  4219. @State isShowDetail:boolean = false
  4220. @State longItemFilePathDetail:string =''
  4221. @Builder
  4222. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  4223. if(
  4224. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4225. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4226. item.name === LocalMusic.STR_HISTORY_MUSIC)
  4227. ){
  4228. //如果是专辑和艺术家的首页,不能长按
  4229. //如果是我的收藏 最近播放等也不能长按
  4230. }else{
  4231. Scroll() {
  4232. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  4233. Menu() {
  4234. MenuItem({
  4235. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  4236. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  4237. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  4238. })
  4239. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4240. .onClick(() => {
  4241. if (item) {
  4242. this.doFav(item)
  4243. }
  4244. this.longItemFilePath = ''
  4245. })
  4246. MenuItem({
  4247. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  4248. content: '下一首播放'
  4249. })
  4250. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4251. .onClick(() => {
  4252. this.addToNextPlay(item);
  4253. this.longItemFilePath = ''
  4254. })
  4255. MenuItem({
  4256. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  4257. content: '添加到歌单'
  4258. })
  4259. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4260. .onClick(async () => {
  4261. this.longItemFilePath = ''
  4262. await this.showAddToPlaylistDialog(item)
  4263. })
  4264. MenuItem({
  4265. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  4266. content: '编辑标签'
  4267. })
  4268. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  4269. height: '99%',
  4270. dragBar: true,
  4271. showClose: true,
  4272. preferType: SheetType.CENTER ,
  4273. title: { title: '编辑标签' }
  4274. })
  4275. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4276. .onClick(async() => {
  4277. this.setEditStrEmpty()
  4278. this.tempLyricContent = await this.getLyricContent(item);
  4279. if(this.isGridMusic||this.twoFingerType==4){
  4280. this.longItemFilePath = item.filePath
  4281. }else{
  4282. this.isShowEdit = !this.isShowEdit;
  4283. }
  4284. })
  4285. MenuItem({
  4286. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  4287. content: $r('app.string.select_all')
  4288. })
  4289. .onClick(() => {
  4290. this.isMultiSelect = !this.isMultiSelect
  4291. this.longItemFilePath = ''
  4292. this.selectedFiles.push(item)
  4293. })
  4294. MenuItem({
  4295. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  4296. content: $r('app.string.rename')
  4297. })
  4298. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4299. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4300. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4301. .onClick(() => {
  4302. this.showReNameDialog(item, index + '', filePath)
  4303. this.longItemFilePath = ''
  4304. })
  4305. MenuItem({
  4306. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  4307. content: $r('app.string.delete')
  4308. })
  4309. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4310. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4311. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4312. .onClick(() => {
  4313. this.selectedFiles.push(item)
  4314. this.showWarnIsDelete()
  4315. this.longItemFilePath = ''
  4316. })
  4317. MenuItem({
  4318. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  4319. content: $r('app.string.detail')
  4320. })
  4321. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  4322. height:'95%',
  4323. dragBar: true,
  4324. showClose: true,
  4325. blurStyle:BlurStyle.Thin,
  4326. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4327. backgroundColor:Color.Transparent,
  4328. title: { title: '详情信息' }
  4329. })
  4330. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4331. .onClick(() => {
  4332. if(this.isGridMusic||this.twoFingerType==4){
  4333. this.longItemFilePathDetail = item.filePath
  4334. }else{
  4335. this.isShowDetail = !this.isShowDetail
  4336. }
  4337. })
  4338. MenuItem({
  4339. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  4340. content: $r('app.string.share')
  4341. })
  4342. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4343. .onClick(() => {
  4344. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4345. this.longItemFilePath = ''
  4346. })
  4347. }
  4348. .font({ size: 15, weight: FontWeight.Normal })
  4349. }
  4350. .width(180)
  4351. }
  4352. .height('auto')
  4353. }
  4354. }
  4355. private listMaxScrollOffsetY: number = 0
  4356. @State selectedIndex: number = -1
  4357. setlistTwoFingers() {
  4358. this.pinchValue = this.scaleValue;
  4359. Logger.info('this.pinchValue = ' + this.pinchValue);
  4360. if (this.pinchValue >= 1) {
  4361. this.twoFingerType++
  4362. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4363. if (this.twoFingerType > 3) {
  4364. this.twoFingerType = 1
  4365. this.isGridMusic = true
  4366. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4367. }
  4368. } else {
  4369. this.twoFingerType--
  4370. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4371. if (this.twoFingerType < 1) {
  4372. this.twoFingerType = 4
  4373. this.columns = 1
  4374. }
  4375. }
  4376. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4377. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4378. this.pinchValue = 1;
  4379. this.scaleValue = 1;
  4380. }
  4381. @Builder
  4382. getList(){
  4383. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  4384. this.getListView()
  4385. }
  4386. .pullDownRatio(this.ratioL)
  4387. .pullToRefresh(true)
  4388. .refreshOffset(0)
  4389. .onOffsetChange((offset: number) => {
  4390. // 越接近最大距离,下拉跟手系数越小。
  4391. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  4392. })
  4393. .onStateChange((refreshStatus: RefreshStatus) => {
  4394. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  4395. })
  4396. .onRefreshing(async () => {
  4397. if(this.modeType==0){
  4398. this.getHistoryList(false)
  4399. this.asyncCurrentPathOnlyFile()
  4400. }else if(this.modeType == 1){
  4401. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4402. }else if(this.modeType == 2){
  4403. workerInstance.postMessage({ code: 3, data: this.context });
  4404. }else if(this.modeType == 3){
  4405. workerInstance.postMessage({ code: 4, data: this.context });
  4406. }else if(this.modeType == 4){
  4407. this.doSongListTask()
  4408. }
  4409. console.log('onRefreshing test');
  4410. })
  4411. }
  4412. // 扫描当前目录下的文件,不扫描子目录
  4413. asyncCurrentPathOnlyFile(){
  4414. if(this.modeType==0){
  4415. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  4416. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  4417. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  4418. if(this.modeType==0){
  4419. this.getSortedFiles(this.currentPath)
  4420. }
  4421. setTimeout(() => {
  4422. this.isRefreshing = false;
  4423. }, 100)
  4424. }).catch((e:object)=>{
  4425. console.info("task1 catch e: " + e);
  4426. })
  4427. }
  4428. }
  4429. @Builder
  4430. getListView() {
  4431. List({ scroller: this.listScroller }) {
  4432. ListItemGroup({ header: this.coverHeader() }) {
  4433. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4434. ListItem() {
  4435. Column() {
  4436. if (item.type === CommonConstants.TYPE_IS_DIR
  4437. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  4438. this.DirItem(item, index)
  4439. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  4440. } else {
  4441. this.MusicItem(item, index)
  4442. }
  4443. }
  4444. .shadow(this.scaleItem === index ? {
  4445. radius: 70,
  4446. color: '#15000000',
  4447. offsetX: 0,
  4448. offsetY: 0
  4449. } :
  4450. {
  4451. radius: 0,
  4452. color: '#15000000',
  4453. offsetX: 0,
  4454. offsetY: 0
  4455. })
  4456. .animation({ curve: Curve.Sharp, duration: 300 })
  4457. }
  4458. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  4459. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  4460. .animation({ duration: 500 }),
  4461. TransitionEffect.scale({ x: 0, y: 0 })))
  4462. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4463. .swipeAction((
  4464. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  4465. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  4466. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  4467. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  4468. .onClick(() => {
  4469. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4470. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4471. this.handleFileSelection(item, !isChecked);
  4472. } else {
  4473. this.doPlay(item, index)
  4474. }
  4475. })
  4476. //拖动List关键代码开始
  4477. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4478. .zIndex(this.dragItem === index ? 1 : 0)
  4479. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4480. .gesture(
  4481. GestureGroup(GestureMode.Sequence,
  4482. LongPressGesture({ repeat: true })
  4483. .onAction((event?: GestureEvent) => {
  4484. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4485. this.scaleItem = index
  4486. })
  4487. })
  4488. .onActionEnd(() => {
  4489. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4490. this.scaleItem = -1
  4491. })
  4492. }),
  4493. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4494. .onActionStart(() => {
  4495. this.dragItem = index // 记录当前拖动项索引
  4496. this.dragRefOffset = 0 // 重置偏移基准
  4497. })
  4498. .onActionUpdate((event: GestureEvent) => {
  4499. this.offsetY = event.offsetY - this.dragRefOffset;
  4500. this.neighborItem = -1;
  4501. let indexA = this.videoLocalList.indexOf(item);
  4502. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4503. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4504. let value: number = 0;
  4505. if (this.offsetY < 0) {
  4506. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4507. this.neighborItem = indexA - 1;
  4508. this.neighborScale = 1 - value / 20;
  4509. } else if (this.offsetY > 0) {
  4510. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4511. this.neighborItem = indexA + 1;
  4512. this.neighborScale = 1 - value / 20;
  4513. }
  4514. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  4515. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4516. this.offsetY -= this.ITEM_INTV;
  4517. this.dragRefOffset += this.ITEM_INTV;
  4518. this.itemMove(indexA, indexA + 1);
  4519. });
  4520. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4521. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4522. this.offsetY += this.ITEM_INTV;
  4523. this.dragRefOffset -= this.ITEM_INTV;
  4524. this.itemMove(indexA, indexA - 1);
  4525. });
  4526. }
  4527. let curListOffset = this.listScroller.currentOffset()
  4528. // 获取手指信息
  4529. let fingerInfo = event.fingerList[0]
  4530. let clickPercentY =
  4531. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  4532. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  4533. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  4534. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  4535. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  4536. }
  4537. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  4538. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  4539. if (curListOffset.yOffset > scrollVelocity + 5) {
  4540. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  4541. }
  4542. }
  4543. })
  4544. .onActionEnd((event: GestureEvent) => {
  4545. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4546. this.dragItem = -1
  4547. this.neighborItem = -1
  4548. })
  4549. animateTo({
  4550. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4551. }, () => {
  4552. this.scaleItem = -1
  4553. })
  4554. })
  4555. )
  4556. .onCancel(() => {
  4557. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4558. this.dragItem = -1
  4559. this.neighborItem = -1
  4560. })
  4561. animateTo({
  4562. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4563. }, () => {
  4564. this.scaleItem = -1
  4565. })
  4566. })
  4567. ) //拖动List关键代码结束
  4568. }, (item: VideoItem) => item.filePath)
  4569. }
  4570. }
  4571. .scrollBar(BarState.Off)
  4572. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4573. .gesture(PinchGesture({ fingers: 2 })
  4574. .onActionEnd((event: GestureEvent) => {
  4575. this.setlistTwoFingers()
  4576. })
  4577. .onActionUpdate(e => {
  4578. this.scaleValue = this.pinchValue * e.scale
  4579. })
  4580. .onActionStart(e => {
  4581. }))
  4582. // .margin(
  4583. // this.isHiCar()&&(this.windowWidth>1800&&this.windowHeight>=1200)?{bottom:this.bottomBarHeight+98}:
  4584. // {
  4585. // bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  4586. // : (this.isShowCoverHeader() ? this.topBarHeight+35 :
  4587. // this.isHiCarSmall()||this.modeType==4?this.topBarHeight+90:this.topBarHeight+165)
  4588. // })
  4589. .margin({
  4590. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  4591. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  4592. })
  4593. .cachedCount(6)
  4594. .reuseId('list_item')
  4595. .borderRadius(20)
  4596. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4597. TransitionEffect.scale({ x: 0, y: 0 })))
  4598. .layoutWeight(1)
  4599. .onScrollIndex((start) => {
  4600. this.selectedIndex = start
  4601. })
  4602. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  4603. .lanes(
  4604. new BreakpointType<number>({
  4605. sm: 1,
  4606. md: 2,
  4607. lg: 2,
  4608. xl: 3,
  4609. xxl: 4
  4610. }).getValue(this.currentBreakpoint),
  4611. new BreakpointType<number>({
  4612. sm: 0,
  4613. md: 12,
  4614. lg: 12,
  4615. xl: 16,
  4616. xxl: 20
  4617. }).getValue(this.currentBreakpoint)
  4618. )
  4619. .onAreaChange((oldValue: Area, newValue: Area) => {
  4620. this.listArea = newValue
  4621. if (this.twoFingerType == 3) {
  4622. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  4623. } else if (this.twoFingerType == 2) {
  4624. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  4625. } else if (this.twoFingerType == 1) {
  4626. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  4627. }
  4628. })
  4629. .onScrollFrameBegin((offset: number) => {
  4630. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  4631. // if (this.isPhoneLan()) {
  4632. // this.setBarHeightHide(offset)
  4633. // } else
  4634. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4635. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4636. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4637. if (this.isScrollHide) {
  4638. this.setBarHeightHide2(offset)
  4639. } else {
  4640. this.setBarHeightNormal()
  4641. }
  4642. } else {
  4643. this.setBarHeightHide(offset)
  4644. }
  4645. return { offsetRemain: offset };
  4646. })
  4647. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  4648. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4649. .onDrop((event?: DragEvent) => {
  4650. try {
  4651. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4652. if (dragData !== undefined) {
  4653. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4654. if (records.length > 0) {
  4655. for (let i = 0; i < records.length; i++) {
  4656. let types = records[i].getTypes();
  4657. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4658. const fileUriUds =
  4659. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4660. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4661. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4662. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4663. this.targetFile = fileUriUds.oriUri;
  4664. this.saveVideoDatas([this.targetFile])
  4665. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4666. }
  4667. }
  4668. }
  4669. } else {
  4670. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4671. }
  4672. } else {
  4673. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4674. }
  4675. } catch (error) {
  4676. const err = error as BusinessError;
  4677. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4678. }
  4679. })
  4680. }
  4681. setBarHeightNormal() {
  4682. this.hideDone = false;
  4683. this.getUIContext().animateTo({
  4684. duration: 300
  4685. }, () => {
  4686. this.bottomBarHeight = 55 + 0;
  4687. this.topBarHeight = 50 + 0;
  4688. this.barOpacity = 1;
  4689. this.barBottomOpacity = 1
  4690. this.currentYOffset = 0;
  4691. this.isHiding = false;
  4692. });
  4693. }
  4694. setBarHeightHide(offset: number) {
  4695. if (offset > 0 && !this.hideDone) {
  4696. this.currentYOffset += offset;
  4697. if (this.currentYOffset <= 100) {
  4698. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  4699. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4700. this.barOpacity = 1 - this.currentYOffset / 100;
  4701. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  4702. } else {
  4703. this.topBarHeight = 0;
  4704. this.bottomBarHeight = 0;
  4705. this.barBottomOpacity = 0
  4706. this.barOpacity = 0;
  4707. this.hideDone = true;
  4708. }
  4709. this.isHiding = true;
  4710. }
  4711. if (offset < 0 && this.isHiding) {
  4712. this.hideDone = false;
  4713. this.getUIContext().animateTo({
  4714. duration: 300
  4715. }, () => {
  4716. this.bottomBarHeight = 55 + 0;
  4717. this.topBarHeight = 50 + 0;
  4718. this.barOpacity = 1;
  4719. this.barBottomOpacity = 1
  4720. this.currentYOffset = 0;
  4721. this.isHiding = false;
  4722. });
  4723. }
  4724. }
  4725. //这个方法没隐藏bottomBar,只隐藏topbar
  4726. setBarHeightHide2(offset: number) {
  4727. if (offset > 0 && !this.hideDone) {
  4728. this.currentYOffset += offset;
  4729. if (this.currentYOffset <= 100) {
  4730. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4731. this.barOpacity = 1 - this.currentYOffset / 100;
  4732. } else {
  4733. this.topBarHeight = 0;
  4734. this.barOpacity = 0;
  4735. this.hideDone = true;
  4736. }
  4737. this.isHiding = true;
  4738. }
  4739. if (offset < 0 && this.isHiding) {
  4740. this.hideDone = false;
  4741. this.getUIContext().animateTo({
  4742. duration: 300
  4743. }, () => {
  4744. this.topBarHeight = 50 + 0;
  4745. this.barOpacity = 1;
  4746. this.currentYOffset = 0;
  4747. this.isHiding = false;
  4748. });
  4749. }
  4750. }
  4751. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  4752. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  4753. switch (item.type) {
  4754. case CommonConstants.TYPE_IS_DIR:
  4755. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  4756. let offsetB = 0
  4757. if(this.twoFingerType==4){
  4758. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4759. let cur = this.waterScroller.currentOffset()
  4760. if (cur && typeof cur.yOffset === 'number') {
  4761. offsetB = cur.yOffset
  4762. }
  4763. }
  4764. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  4765. }else
  4766. if (this.isGridMusic) {
  4767. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4768. let cur = this.scroller.currentOffset()
  4769. if (cur && typeof cur.yOffset === 'number') {
  4770. offsetB = cur.yOffset
  4771. }
  4772. }
  4773. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  4774. } else {
  4775. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4776. let cur = this.listScroller.currentOffset()
  4777. if (cur && typeof cur.yOffset === 'number') {
  4778. offsetB = cur.yOffset
  4779. }
  4780. }
  4781. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  4782. }
  4783. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  4784. this.showVerifyDialog()
  4785. this.currentTitleName = '私密音频'
  4786. this.currentTitleCover = $r('app.media.ic_avatar5')
  4787. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  4788. this.titleBarModel.setTitleName('最近播放')
  4789. this.currentTitleCover = $r('app.media.ic_avatar2')
  4790. this.currentTitleName = '最近播放'
  4791. //加载动画效果
  4792. this.updateListData(this.historyList, true)
  4793. // this.videoLocalList = this.historyList
  4794. if (ArrayUtil.isEmpty(this.historyList)) {
  4795. ToastUtil.showToast('最近播放记录空空如也')
  4796. } else {
  4797. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  4798. }
  4799. this.isHistory = true
  4800. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4801. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  4802. this.titleBarModel.setTitleName('我的收藏')
  4803. this.currentTitleName = '我的收藏'
  4804. this.currentTitleCover = $r('app.media.ic_avatar1')
  4805. //加载动画效果
  4806. this.updateListData(this.favList)
  4807. if (ArrayUtil.isEmpty(this.favList)) {
  4808. ToastUtil.showToast('无音乐收藏记录')
  4809. } else {
  4810. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  4811. }
  4812. this.isFavMusic = true
  4813. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4814. } else {
  4815. this.currentTitleName = item.name
  4816. this.currentPath = item.filePath
  4817. this.currentTitleCover = $r('app.media.ic_avatar5')
  4818. this.getSortedFiles(this.currentPath)
  4819. }
  4820. //进入歌单的时候的滚动位置在顶部
  4821. if(this.twoFingerType==4){
  4822. setTimeout(() => {
  4823. this.waterScroller.scrollEdge(Edge.Top)
  4824. this.scroller.scrollEdge(Edge.Top)
  4825. }, 380)
  4826. }else{
  4827. if (this.isGridMusic) {
  4828. this.scroller.scrollEdge(Edge.Top)
  4829. }else{
  4830. this.listScroller.scrollEdge(Edge.Top)
  4831. }
  4832. }
  4833. break;
  4834. case CommonConstants.TYPE_IS_ARTIST:
  4835. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  4836. let offsetA = 0
  4837. if(this.twoFingerType==4){
  4838. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4839. let cur = this.waterScroller.currentOffset()
  4840. if (cur && typeof cur.yOffset === 'number') {
  4841. offsetA = cur.yOffset
  4842. }
  4843. }
  4844. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  4845. }else
  4846. if (this.isGridMusic) {
  4847. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4848. let cur = this.scroller.currentOffset()
  4849. if (cur && typeof cur.yOffset === 'number') {
  4850. offsetA = cur.yOffset
  4851. }
  4852. }
  4853. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  4854. } else {
  4855. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4856. let cur = this.listScroller.currentOffset()
  4857. if (cur && typeof cur.yOffset === 'number') {
  4858. offsetA = cur.yOffset
  4859. }
  4860. }
  4861. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  4862. }
  4863. let mList = this.artistMap.get(item.name)
  4864. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  4865. Utility.doSortListAscending(mList)
  4866. this.isCanBack = true
  4867. this.titleBarModel.setTitleName(item.name)
  4868. this.currentTitleName = '艺术家:' + item.name
  4869. if (item.pixelMapPath) {
  4870. this.currentTitleCover = item.pixelMapPath
  4871. }
  4872. this.updateListData(mList)
  4873. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4874. }
  4875. //进入歌单的时候的滚动位置在顶部
  4876. if(this.twoFingerType==4){
  4877. setTimeout(() => {
  4878. this.waterScroller.scrollEdge(Edge.Top)
  4879. this.scroller.scrollEdge(Edge.Top)
  4880. }, 380)
  4881. }else{
  4882. if (this.isGridMusic) {
  4883. this.scroller.scrollEdge(Edge.Top)
  4884. }else{
  4885. this.listScroller.scrollEdge(Edge.Top)
  4886. }
  4887. }
  4888. break;
  4889. case CommonConstants.TYPE_IS_ALBUM:
  4890. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  4891. let offset = 0
  4892. if(this.twoFingerType==4){
  4893. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4894. let cur = this.waterScroller.currentOffset()
  4895. if (cur && typeof cur.yOffset === 'number') {
  4896. offset = cur.yOffset
  4897. }
  4898. }
  4899. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  4900. }else
  4901. if (this.isGridMusic) {
  4902. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4903. let cur = this.scroller.currentOffset()
  4904. if (cur && typeof cur.yOffset === 'number') {
  4905. offset = cur.yOffset
  4906. }
  4907. }
  4908. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  4909. } else {
  4910. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4911. let cur = this.listScroller.currentOffset()
  4912. if (cur && typeof cur.yOffset === 'number') {
  4913. offset = cur.yOffset
  4914. }
  4915. }
  4916. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4917. }
  4918. let albumList = this.albumMap.get(item.name)
  4919. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4920. Utility.doSortListAscending(albumList)
  4921. this.isCanBack = true
  4922. this.titleBarModel.setTitleName(item.name)
  4923. this.currentTitleName = '专辑:' + item.name
  4924. if (item.pixelMapPath) {
  4925. this.currentTitleCover = item.pixelMapPath
  4926. }
  4927. this.updateListData(albumList)
  4928. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4929. this.mScrollMap.set(item.name, this.selectedIndex)
  4930. }
  4931. //进入歌单的时候的滚动位置在顶部
  4932. if(this.twoFingerType==4){
  4933. setTimeout(() => {
  4934. this.waterScroller.scrollEdge(Edge.Top)
  4935. this.scroller.scrollEdge(Edge.Top)
  4936. }, 380)
  4937. }else{
  4938. if (this.isGridMusic) {
  4939. this.scroller.scrollEdge(Edge.Top)
  4940. }else{
  4941. this.listScroller.scrollEdge(Edge.Top)
  4942. }
  4943. }
  4944. break;
  4945. case CommonConstants.TYPE_IS_CSJAD:
  4946. return
  4947. break;
  4948. case CommonConstants.TYPE_LOCAL:
  4949. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  4950. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  4951. const cueTracks:CueTrack[] = cueinfo.tracks
  4952. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  4953. if(ArrayUtil.isNotEmpty(cueTracks)){
  4954. this.showCueDialog(cueTracks,cueinfo)
  4955. }
  4956. // this.showCueSheet = !this.showCueSheet
  4957. return
  4958. }
  4959. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4960. this.stop();
  4961. }
  4962. if (isOpen) {
  4963. this.currentSong = item
  4964. if (index !== undefined) {
  4965. this.curIndex = index
  4966. }
  4967. this.songList = []
  4968. this.songList.push(item)
  4969. this.sonDataSource.pushArrayData(this.songList)
  4970. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  4971. this.currentSong = item
  4972. if (index !== undefined) {
  4973. this.curIndex = index
  4974. }
  4975. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  4976. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  4977. }else {
  4978. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4979. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4980. this.songList = globalVideoList
  4981. this.sonDataSource.pushArrayData(this.songList)
  4982. this.currentSong = globalVideoList[this.curIndex]
  4983. }
  4984. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  4985. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  4986. this.name = this.currentSong.name
  4987. this.cover = this.currentSong.pixelMapPath
  4988. this.artist = this.currentSong.artist
  4989. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  4990. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  4991. this.startPlayOrResumePlay()
  4992. break;
  4993. case CommonConstants.TYPE_WEBDAV:
  4994. // 处理网络音频播放(WebDAV)
  4995. Logger.info(`heanup 处理网络音频播放: ${item.name}, URL: ${item.filePath}`)
  4996. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4997. this.stop();
  4998. }
  4999. if (isOpen) {
  5000. this.currentSong = item
  5001. if (index !== undefined) {
  5002. this.curIndex = index
  5003. }
  5004. this.songList = []
  5005. this.songList.push(item)
  5006. this.sonDataSource.pushArrayData(this.songList)
  5007. } else if (isFromSonPlayList) {
  5008. // 点击来自右下角的播放列表
  5009. this.currentSong = item
  5010. if (index !== undefined) {
  5011. this.curIndex = index
  5012. }
  5013. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5014. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5015. } else {
  5016. // 从全局网络音频列表中查找
  5017. let globalVideoList = this.videoLocalList.filter(video => video.type === CommonConstants.TYPE_WEBDAV) as VideoItem[];
  5018. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  5019. if (this.curIndex === -1 && index !== undefined) {
  5020. this.curIndex = index;
  5021. }
  5022. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  5023. this.currentSong = this.songList[this.curIndex];
  5024. this.sonDataSource.pushArrayData(this.songList)
  5025. }
  5026. AppStorage.setOrCreate('currentSong', this.currentSong);
  5027. // 对WebDAV URL进行编码处理,确保空格等特殊字符被正确编码
  5028. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  5029. this.name = this.currentSong.name
  5030. this.cover = this.currentSong.pixelMapPath
  5031. this.artist = this.currentSong.artist
  5032. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 编码后URL: ${this.videoUrl}`)
  5033. this.startPlayOrResumePlay()
  5034. break;
  5035. }
  5036. }
  5037. private cueComponentId: number = 0
  5038. //显示cue分轨列表对话框
  5039. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  5040. this.getUIContext().getPromptAction().openCustomDialog({
  5041. builder: () => {
  5042. this.cueComptentBuilder(cueTracks,cueinfo)
  5043. },
  5044. isModal:true,
  5045. showInSubWindow:false,
  5046. maskColor: Color.Transparent,
  5047. dialogTransition: // 设置弹窗内容显示的过渡效果
  5048. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  5049. .animation({ duration: 600, curve: Curve.Smooth }),
  5050. maskTransition: // 设置蒙层显示的过渡效果
  5051. TransitionEffect.opacity(0.5)
  5052. .animation({ duration: 600, curve: Curve.Smooth })
  5053. }).then((dialogId: number) => {
  5054. this.cueComponentId = dialogId
  5055. })
  5056. .catch((error: BusinessError) => {
  5057. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5058. })
  5059. }
  5060. @Builder
  5061. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  5062. CueComptent({
  5063. title:cueinfo.title,
  5064. cueTracks:cueTracks,
  5065. isLongNameRoLL:this.isLongNameRoLL,
  5066. onCancel:()=>{
  5067. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  5068. },
  5069. onDoItemClick:(item: CueTrack, index: number)=>{
  5070. //获取cueinfo对应的filePath
  5071. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5072. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  5073. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  5074. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  5075. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  5076. if (this.currentSong){
  5077. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5078. this.stop();//播放之前先停止之前播放。
  5079. }
  5080. this.songList = globalVideoList
  5081. this.sonDataSource.pushArrayData(this.songList)
  5082. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  5083. this.name = item.title||this.currentSong.name
  5084. this.cover = this.currentSong.pixelMapPath
  5085. this.artist = item.performer||this.currentSong.artist
  5086. this.currentSong.name = this.name
  5087. this.currentSong.artist = this.artist
  5088. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5089. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  5090. }
  5091. }
  5092. })
  5093. }
  5094. @Builder
  5095. PlayController() {
  5096. Column() {
  5097. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  5098. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5099. Row() {
  5100. if(this.isHiCar()){
  5101. this.playConRigth()
  5102. Column(){
  5103. this.centerName()
  5104. }.layoutWeight(1)
  5105. .onClick(()=>{
  5106. this.showPlayerView()
  5107. })
  5108. this.playConLeft(false)
  5109. }else{
  5110. this.playConLeft()
  5111. this.playConRigth()
  5112. }
  5113. }
  5114. .width('100%')
  5115. .height(this.bottomBarHeight)
  5116. .justifyContent(FlexAlign.Center)
  5117. .hitTestBehavior(HitTestMode.Transparent)
  5118. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  5119. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  5120. // modalTransition: ModalTransition.DEFAULT,
  5121. transition: AnimationHelper.transitionInDown(666),
  5122. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  5123. })
  5124. .padding({
  5125. left: 16,
  5126. right: 16
  5127. })
  5128. Line()
  5129. .width('100%')
  5130. .height(25)
  5131. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  5132. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5133. }
  5134. .clickEffect({ level: ClickEffectLevel.HEAVY })
  5135. }
  5136. @State isFrontWhite: boolean = false
  5137. @Builder
  5138. centerName() {
  5139. Column() {
  5140. Text(this.currentSong?.name)
  5141. .fontSize(16)
  5142. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5143. .maxLines(1)
  5144. .fontColor($r('app.color.text_color'))
  5145. .fontWeight(500);
  5146. Row() {
  5147. Text(this.currentSong?.artist)
  5148. .margin({ top: 2 })
  5149. .fontSize(13)
  5150. .textAlign(TextAlign.Start)
  5151. .maxLines(1)
  5152. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5153. .fontColor($r('app.color.text_color'));
  5154. }
  5155. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5156. }
  5157. .alignItems(HorizontalAlign.Center)
  5158. }
  5159. @Builder
  5160. playConLeft(isLeft: boolean = true) {
  5161. Row() {
  5162. RotatingCover({ songLabel: this.currentSong?.pixelMapPath });
  5163. Column() {
  5164. Text(this.currentSong?.name)
  5165. .fontSize(16)
  5166. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5167. .maxLines(1)
  5168. .fontColor($r('app.color.text_color'))
  5169. .fontWeight(500);
  5170. Row() {
  5171. Text(this.currentSong?.artist)
  5172. .margin({ top: 2 })
  5173. .fontSize(13)
  5174. .textAlign(TextAlign.Start)
  5175. .maxLines(1)
  5176. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5177. .fontColor($r('app.color.text_color'));
  5178. }
  5179. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5180. }
  5181. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  5182. .margin({ right: isLeft?22:10 })
  5183. .visibility(isLeft? Visibility.Visible:Visibility.None)
  5184. }
  5185. .padding({ right: 18 })
  5186. .layoutWeight(isLeft?1:0)
  5187. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5188. .onClick(() => {
  5189. this.showPlayerView()
  5190. })
  5191. }
  5192. //打开播放页
  5193. showPlayerView() {
  5194. if (ArrayUtil.isNotEmpty(this.songList)) {
  5195. this.isShowPlay = true;
  5196. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  5197. this.initLyric(lyricPath);
  5198. this.startAutoHide();
  5199. } else {
  5200. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  5201. }
  5202. }
  5203. @Builder
  5204. playConRigth() {
  5205. Row() {
  5206. Image($r('app.media.hm_previous'))
  5207. .height(28)
  5208. .width(28)
  5209. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5210. .margin({ left: 8, right: 16 })
  5211. .fillColor(this.themeColor)
  5212. .displayPriority(2)
  5213. .onClick(() => {
  5214. if (ArrayUtil.isNotEmpty(this.songList)) {
  5215. this.playPrevious()
  5216. } else {
  5217. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5218. }
  5219. })
  5220. //播放进度条
  5221. Stack() {
  5222. Progress({
  5223. value: Math.floor(this.progressValue),
  5224. type: ProgressType.Ring,
  5225. })
  5226. .color(this.themeColor)// 进度条前景色为灰色
  5227. .backgroundColor($r('app.color.index_background'))
  5228. .height(40)
  5229. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5230. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  5231. .height(38)
  5232. .width(38)
  5233. .displayPriority(3)
  5234. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5235. .fillColor(this.themeColor)
  5236. .onClick(() => {
  5237. if (ArrayUtil.isNotEmpty(this.songList)) {
  5238. console.info('onecold playOrPause 4642')
  5239. this.playOrPause()
  5240. } else {
  5241. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5242. }
  5243. })
  5244. }
  5245. Image($r('app.media.hm_next'))
  5246. .height(28)
  5247. .width(28)
  5248. .margin({
  5249. right: 16,
  5250. left: 16
  5251. })
  5252. .fillColor(this.themeColor)
  5253. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5254. .displayPriority(2)
  5255. .onClick(() => {
  5256. if (ArrayUtil.isNotEmpty(this.songList)) {
  5257. this.playNext()
  5258. } else {
  5259. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5260. }
  5261. })
  5262. Image($r('app.media.hm_playlist'))
  5263. .height(28)
  5264. .width(28)
  5265. .displayPriority(1)
  5266. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5267. .fillColor(this.themeColor)
  5268. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  5269. height: '95%',
  5270. dragBar: true,
  5271. showClose: true,
  5272. blurStyle: BlurStyle.Thin,
  5273. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5274. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  5275. title: {
  5276. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5277. + `(${this.songList.length}首)`
  5278. }
  5279. })
  5280. .onClick(() => {
  5281. if (ArrayUtil.isNotEmpty(this.songList)) {
  5282. this.isShowSheet = !this.isShowSheet;
  5283. this.isFrontWhite = false
  5284. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  5285. this.scrollIndex()
  5286. } else {
  5287. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5288. }
  5289. })
  5290. }
  5291. }
  5292. scrollIndex(){
  5293. try {
  5294. setTimeout(() => {
  5295. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  5296. if(this.curIndex>60){
  5297. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  5298. }else{
  5299. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5300. }
  5301. })
  5302. }, 123)
  5303. }catch (error) {
  5304. console.error(`onecold scrollIndex出错: ${error}`);
  5305. }
  5306. }
  5307. //播放列表布局
  5308. @Builder
  5309. PlayListSheet() {
  5310. Column() {
  5311. this.PlayList()
  5312. }
  5313. .width('100%')
  5314. .height('100%')
  5315. }
  5316. @State titleStr: string = ''
  5317. @State ablumStr: string = ''
  5318. @State artistStr: string = ''
  5319. @State lyricConStr: string = ''
  5320. @State currentEditItem: string = ''
  5321. @State yearStr: string = ''
  5322. @State trackStr: string = ''
  5323. @State genreStr: string = ''
  5324. @State imagePathStr: string = ''
  5325. @State albumArtistStr: string = ''
  5326. @State composerStr: string = ''
  5327. @State lyricistStr: string = ''
  5328. @State commentStr: string = ''
  5329. @State discStr: string = ''
  5330. doUpdateData() {
  5331. setTimeout(() => {
  5332. if (this.modeType === 0) {
  5333. this.deleteCache(this.currentPath)
  5334. this.getSortedFiles(this.currentPath)
  5335. }
  5336. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5337. workerInstance.postMessage({ code: 3, data: this.context });
  5338. workerInstance.postMessage({ code: 4, data: this.context });
  5339. }, 999)
  5340. }
  5341. //编辑信息
  5342. async doEdit(item: VideoItem) {
  5343. if (!item) {
  5344. return
  5345. }
  5346. if (StrUtil.isEmpty(this.titleStr)) {
  5347. ToastUtil.showToast('标题不能为空')
  5348. return
  5349. }
  5350. //用户更改了封面,那就内嵌下封面
  5351. if(StrUtil.isNotEmpty(this.imagePathStr)){
  5352. const resultCover:boolean = await changeMusicCover(this.context,
  5353. item.filePath,this.imagePathStr,true);
  5354. this.imagePathStr = ''
  5355. if(resultCover){
  5356. ToastUtil.showToast('内嵌封面成功')
  5357. }
  5358. }
  5359. const metadata:FFMpegTags = {
  5360. title: this.titleStr,
  5361. artist: this.artistStr,
  5362. album: this.ablumStr,
  5363. TYER:this.yearStr,
  5364. genre:this.genreStr,
  5365. track:this.trackStr,
  5366. album_artist:this.albumArtistStr,
  5367. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  5368. COMPOSER:this.composerStr,
  5369. lyricist:this.lyricistStr,
  5370. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  5371. comment:this.commentStr,
  5372. disc:this.discStr,
  5373. };
  5374. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  5375. const result:boolean = await repairAudioMetadata(
  5376. item.filePath,
  5377. this.lyricConStr,
  5378. metadata,
  5379. true
  5380. );
  5381. if (result) {
  5382. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  5383. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  5384. (success: boolean, error?: string) => {
  5385. // this.isShowEdit = false
  5386. if (success) {
  5387. console.log(" onecold 编辑信息成功,数据库已同步");
  5388. ToastUtil.showToast('内嵌音乐标签成功')
  5389. this.isShowMoreView = false
  5390. this.name = this.titleStr
  5391. if (item.filePath == this.currentSong?.filePath) {
  5392. this.currentSong.name = this.titleStr
  5393. this.artist = this.artistStr
  5394. this.currentSong.artist = this.artistStr
  5395. this.currentSong.album = this.ablumStr
  5396. this.currentSong.year = this.yearStr
  5397. this.currentSong.genre = this.genreStr
  5398. this.currentSong.track = this.trackStr
  5399. this.currentSong.lyricContent = this.lyricConStr
  5400. this.initLyric(item.filePath)
  5401. this.currentSong.ALBUMARTIST = this.albumArtistStr
  5402. this.currentSong.COMPOSER = this.composerStr
  5403. this.currentSong.LYRICIST = this.lyricistStr
  5404. this.currentSong.COMMENT = this.commentStr
  5405. }
  5406. this.doUpdateData()
  5407. } else {
  5408. // ToastUtil.showToast('保存失败' + error?.toString())
  5409. console.error(" onecold 编辑信息数据库失败原因: " + error);
  5410. }
  5411. });
  5412. console.log(' onecold 元数据标签更新成功,');
  5413. } else {
  5414. ToastUtil.showToast('内嵌音乐标签失败')
  5415. console.log('onecold 内嵌音乐标签失败');
  5416. }
  5417. this.longItemFilePath = ''
  5418. this.tempLyricContent = ''
  5419. this.isShowEdit = false
  5420. }
  5421. updateLyricToDB() {
  5422. }
  5423. @Builder
  5424. editSheet(item: VideoItem) {
  5425. Scroll() {
  5426. Column() {
  5427. this.editDetail(item)
  5428. }
  5429. }
  5430. .width('100%')
  5431. .height('100%')
  5432. }
  5433. @Builder
  5434. editDetail(item: VideoItem) {
  5435. Column() {
  5436. if (item) {
  5437. Row() {
  5438. Stack() {
  5439. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  5440. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  5441. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  5442. item.pixelMapPath)
  5443. .fillColor(this.themeColor)
  5444. .height(88)
  5445. .width(88)
  5446. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5447. .borderRadius(12)
  5448. .clip(true)
  5449. .opacity(this.opacityItem)// 绑定透明度
  5450. .margin({ left: 25 })
  5451. }
  5452. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5453. .onClick(async () => {
  5454. const imagePath:string | undefined = await this.goSelectImage(item);
  5455. if (imagePath) {
  5456. //用户更改过图片
  5457. this.imagePathStr = imagePath
  5458. }
  5459. })
  5460. .width('28%')
  5461. Row() {
  5462. Column() {
  5463. Text(item.name)
  5464. .fontSize(17)
  5465. .maxLines(1)
  5466. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5467. .animation({
  5468. duration: 555,
  5469. curve: 'Linear',
  5470. })
  5471. .fontColor(this.themeColor)
  5472. .margin({ left: 8 })
  5473. Row() {
  5474. Text(item.artist)
  5475. .fontSize(14)
  5476. .maxLines(1)
  5477. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5478. .padding({ top: 8 })
  5479. .fontColor(this.themeColor)
  5480. .margin({ left: 8 })
  5481. }
  5482. }
  5483. .height('100%')
  5484. .width(100)
  5485. .layoutWeight(1)
  5486. .justifyContent(FlexAlign.Center)
  5487. .alignItems(HorizontalAlign.Start)
  5488. Column() {
  5489. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5490. Row(){
  5491. SymbolGlyph($r('sys.symbol.picture'))
  5492. .fontSize(18)
  5493. .fontColor([Color.White])
  5494. Text('获取封面')
  5495. .margin({ left: 4 })
  5496. .fontSize(11)
  5497. .fontColor(Color.White)
  5498. .fontWeight(480)
  5499. .textAlign(TextAlign.Center)
  5500. }
  5501. .justifyContent(FlexAlign.Center)
  5502. }
  5503. .height(38)
  5504. .width(100)
  5505. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5506. .backgroundColor(this.themeColor)
  5507. .stateEffect(true)
  5508. .margin({ right: 35 })
  5509. .onClick(async () => {
  5510. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  5511. this.showTipsDialog();
  5512. return; // Return empty string when no API is configured
  5513. }
  5514. const imagePath:string | undefined = await this.doSearchCover(item);
  5515. console.info('onecold imagePath = '+imagePath)
  5516. if (StrUtil.isNotEmpty(imagePath)) {
  5517. //用户更改过图片
  5518. this.imagePathStr = imagePath
  5519. ToastUtil.showToast('获取封面成功')
  5520. }else{
  5521. ToastUtil.showToast('获取封面失败,请重试')
  5522. }
  5523. })
  5524. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5525. Row(){
  5526. SymbolGlyph($r('sys.symbol.input_mode'))
  5527. .fontSize(18)
  5528. .fontColor([Color.White])
  5529. Text('获取歌词')
  5530. .margin({ left: 4 })
  5531. .fontSize(11)
  5532. .fontColor(Color.White)
  5533. .fontWeight(480)
  5534. .textAlign(TextAlign.Center)
  5535. }
  5536. .justifyContent(FlexAlign.Center)
  5537. }
  5538. .height(38)
  5539. .width(100)
  5540. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5541. .backgroundColor(this.themeColor)
  5542. .stateEffect(true)
  5543. .margin({ top: 9, right: 35 })
  5544. .onClick(async () => {
  5545. //判断有没有设置api
  5546. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  5547. if (StrUtil.isEmpty(apiUrl)) {
  5548. this.isLyricSetting = false
  5549. this.showTipsDialog()
  5550. return
  5551. }
  5552. let artist = item.artist
  5553. let title = item.name
  5554. if(!artist)
  5555. artist = ''
  5556. if(!title)
  5557. title = ''
  5558. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  5559. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5560. this.lyricConStr = res;
  5561. ToastUtil.showToast('获取歌词成功')
  5562. }else{
  5563. ToastUtil.showToast('获取歌词失败,请重试')
  5564. }
  5565. })
  5566. }
  5567. .justifyContent(FlexAlign.Start)
  5568. }
  5569. .height('100%')
  5570. .justifyContent(FlexAlign.Start)
  5571. .layoutWeight(1)
  5572. }
  5573. .width('100%')
  5574. .height(98)
  5575. Row() {
  5576. Text('标题:')
  5577. .fontSize(14)
  5578. .fontColor($r('app.color.text_color'))
  5579. .margin({ left: 22 })
  5580. TextInput({ text: item.name })
  5581. .height(40)
  5582. .maxLines(1)
  5583. .fontSize(14)
  5584. .layoutWeight(1)
  5585. .fontColor($r('app.color.text_color'))
  5586. .margin({ right: 20, left: 10 })
  5587. .onChange((val: string) => {
  5588. this.titleStr = val
  5589. })
  5590. }
  5591. .width('100%')
  5592. .margin({ top: 10, bottom: 10 })
  5593. .justifyContent(FlexAlign.Start)
  5594. Row() {
  5595. Text('艺术家:')
  5596. .fontSize(14)
  5597. .fontColor($r('app.color.text_color'))
  5598. .margin({ left: 22 })
  5599. TextInput({ text: item.artist })
  5600. .height(40)
  5601. .maxLines(1)
  5602. .fontSize(14)
  5603. .layoutWeight(1)
  5604. .fontColor($r('app.color.text_color'))
  5605. .margin({ right: 20, left: 10 })
  5606. .onChange((val: string) => {
  5607. this.artistStr = val
  5608. })
  5609. }
  5610. .width('100%')
  5611. .margin({ top: 10, bottom: 10 })
  5612. .justifyContent(FlexAlign.Start)
  5613. Row() {
  5614. Text('专辑名:')
  5615. .fontSize(14)
  5616. .fontColor($r('app.color.text_color'))
  5617. .margin({ left: 22 })
  5618. TextInput({ text: item.album })
  5619. .height(40)
  5620. .maxLines(1)
  5621. .fontSize(14)
  5622. .layoutWeight(1)
  5623. .fontColor($r('app.color.text_color'))
  5624. .margin({ right: 20, left: 10 })
  5625. .onChange((val: string) => {
  5626. this.ablumStr = val
  5627. })
  5628. }
  5629. .width('100%')
  5630. .margin({ top: 10, bottom: 10 })
  5631. .justifyContent(FlexAlign.Start)
  5632. Row() {
  5633. Column(){
  5634. Column(){
  5635. Text('歌词:')
  5636. .fontSize(14)
  5637. .fontColor($r('app.color.text_color'))
  5638. .margin({ top:9,left: 22 })
  5639. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5640. SymbolGlyph($r('sys.symbol.trash_fill'))
  5641. .fontSize(25)
  5642. .alignSelf(ItemAlign.Center)
  5643. .margin({ left: 22,top:25})
  5644. }
  5645. .backgroundColor(Color.Transparent)
  5646. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5647. Visibility.None:Visibility.Visible)
  5648. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5649. .onClick(()=>{
  5650. this.lyricConStr = ''
  5651. this.lyricContent = ''
  5652. this.tempLyricContent = ''
  5653. })
  5654. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5655. SymbolGlyph($r('sys.symbol.plus'))
  5656. .fontSize(25)
  5657. .alignSelf(ItemAlign.Center)
  5658. .margin({ left: 22,top:25})
  5659. }
  5660. .backgroundColor(Color.Transparent)
  5661. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5662. .onClick( ()=>{
  5663. this.callFilePickerSelectFileForLyric()
  5664. })
  5665. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5666. SymbolGlyph($r('sys.symbol.traditional_square'))
  5667. .fontSize(25)
  5668. .alignSelf(ItemAlign.Center)
  5669. .margin({ left: 22,top:25})
  5670. }
  5671. .backgroundColor(Color.Transparent)
  5672. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5673. Visibility.None:Visibility.Visible)
  5674. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5675. .onClick( ()=>{
  5676. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5677. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  5678. })
  5679. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5680. Image($r('app.media.jianti'))
  5681. .height(25)
  5682. .fillColor($r('app.color.text_color'))
  5683. .alignSelf(ItemAlign.Center)
  5684. .margin({ left: 22,top:25})
  5685. }
  5686. .backgroundColor(Color.Transparent)
  5687. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5688. Visibility.None:Visibility.Visible)
  5689. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5690. .onClick( ()=>{
  5691. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5692. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  5693. })
  5694. }
  5695. .layoutWeight(1)
  5696. }
  5697. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  5698. this.tempLyricContent })
  5699. .type(TextAreaType.NORMAL)
  5700. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  5701. .fontSize(14)
  5702. .layoutWeight(1)
  5703. .fontColor($r('app.color.text_color'))
  5704. .margin({ right: 20, left: 10 })
  5705. .onChange((val: string) => {
  5706. this.lyricConStr = val
  5707. })
  5708. }
  5709. .width('100%')
  5710. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  5711. .margin({ top: 10, bottom: 10 })
  5712. .justifyContent(FlexAlign.Start)
  5713. Row() {
  5714. Text('年份:')
  5715. .fontSize(14)
  5716. .fontColor($r('app.color.text_color'))
  5717. .margin({ left: 22 })
  5718. TextInput({ text: item.year })
  5719. .height(40)
  5720. .maxLines(1)
  5721. .fontSize(14)
  5722. .type(InputType.Number)
  5723. .layoutWeight(1)
  5724. .fontColor($r('app.color.text_color'))
  5725. .margin({ right: 20, left: 10 })
  5726. .onChange((val: string) => {
  5727. this.yearStr = val
  5728. })
  5729. }
  5730. .width('100%')
  5731. .margin({ top: 10, bottom: 10 })
  5732. .justifyContent(FlexAlign.Start)
  5733. Row() {
  5734. Text('音轨号:')
  5735. .fontSize(14)
  5736. .fontColor($r('app.color.text_color'))
  5737. .margin({ left: 22 })
  5738. TextInput({ text:item.track=='未知'?'': item.track })
  5739. .height(40)
  5740. .maxLines(1)
  5741. .fontSize(14)
  5742. .type(InputType.Number)
  5743. .layoutWeight(1)
  5744. .fontColor($r('app.color.text_color'))
  5745. .margin({ right: 20, left: 10 })
  5746. .onChange((val: string) => {
  5747. this.trackStr = val
  5748. })
  5749. }
  5750. .width('100%')
  5751. .margin({ top: 10, bottom: 10 })
  5752. .justifyContent(FlexAlign.Start)
  5753. Row() {
  5754. Text('碟号:')
  5755. .fontSize(14)
  5756. .fontColor($r('app.color.text_color'))
  5757. .margin({ left: 22 })
  5758. TextInput({ text:item.disc })
  5759. .height(40)
  5760. .maxLines(1)
  5761. .fontSize(14)
  5762. .type(InputType.Number)
  5763. .layoutWeight(1)
  5764. .fontColor($r('app.color.text_color'))
  5765. .margin({ right: 20, left: 10 })
  5766. .onChange((val: string) => {
  5767. this.discStr = val
  5768. })
  5769. }
  5770. .width('100%')
  5771. .margin({ top: 10, bottom: 10 })
  5772. .justifyContent(FlexAlign.Start)
  5773. Row() {
  5774. Text('风格:')
  5775. .fontSize(14)
  5776. .fontColor($r('app.color.text_color'))
  5777. .margin({ left: 22 })
  5778. TextInput({ text: item.genre })
  5779. .height(40)
  5780. .maxLines(1)
  5781. .fontSize(14)
  5782. .layoutWeight(1)
  5783. .fontColor($r('app.color.text_color'))
  5784. .margin({ right: 20, left: 10 })
  5785. .onChange((val: string) => {
  5786. this.genreStr = val
  5787. })
  5788. }
  5789. .width('100%')
  5790. .margin({ top: 10, bottom: 10 })
  5791. .justifyContent(FlexAlign.Start)
  5792. Row() {
  5793. Text('专辑艺术家:')
  5794. .fontSize(14)
  5795. .fontColor($r('app.color.text_color'))
  5796. .margin({ left: 22 })
  5797. TextInput({ text: item.ALBUMARTIST })
  5798. .height(40)
  5799. .maxLines(1)
  5800. .fontSize(14)
  5801. .layoutWeight(1)
  5802. .fontColor($r('app.color.text_color'))
  5803. .margin({ right: 20, left: 10 })
  5804. .onChange((val: string) => {
  5805. this.albumArtistStr = val
  5806. })
  5807. }
  5808. .width('100%')
  5809. .margin({ top: 10, bottom: 10 })
  5810. .justifyContent(FlexAlign.Start)
  5811. Row() {
  5812. Text('作曲:')
  5813. .fontSize(14)
  5814. .fontColor($r('app.color.text_color'))
  5815. .margin({ left: 22 })
  5816. TextInput({ text: item.COMPOSER })
  5817. .height(40)
  5818. .maxLines(1)
  5819. .fontSize(14)
  5820. .layoutWeight(1)
  5821. .fontColor($r('app.color.text_color'))
  5822. .margin({ right: 20, left: 10 })
  5823. .onChange((val: string) => {
  5824. this.composerStr = val
  5825. })
  5826. }
  5827. .width('100%')
  5828. .margin({ top: 10, bottom: 10 })
  5829. .justifyContent(FlexAlign.Start)
  5830. Row() {
  5831. Text('作词:')
  5832. .fontSize(14)
  5833. .fontColor($r('app.color.text_color'))
  5834. .margin({ left: 22 })
  5835. TextInput({ text: item.LYRICIST })
  5836. .height(40)
  5837. .maxLines(1)
  5838. .fontSize(14)
  5839. .layoutWeight(1)
  5840. .fontColor($r('app.color.text_color'))
  5841. .margin({ right: 20, left: 10 })
  5842. .onChange((val: string) => {
  5843. this.lyricistStr = val
  5844. })
  5845. }
  5846. .width('100%')
  5847. .margin({ top: 10, bottom: 10 })
  5848. .justifyContent(FlexAlign.Start)
  5849. Row() {
  5850. Text('注释:')
  5851. .fontSize(14)
  5852. .fontColor($r('app.color.text_color'))
  5853. .margin({ left: 22 })
  5854. TextInput({ text: item.COMMENT })
  5855. .height(40)
  5856. .maxLines(1)
  5857. .fontSize(14)
  5858. .layoutWeight(1)
  5859. .fontColor($r('app.color.text_color'))
  5860. .margin({ right: 20, left: 10 })
  5861. .onChange((val: string) => {
  5862. this.commentStr = val
  5863. })
  5864. }
  5865. .width('100%')
  5866. .margin({ top: 10, bottom: 10 })
  5867. .justifyContent(FlexAlign.Start)
  5868. Row() {
  5869. Button('保存')
  5870. .fontColor(Color.White)
  5871. .layoutWeight(1)
  5872. .height(50)
  5873. .width(100)
  5874. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5875. .backgroundColor(this.themeColor)
  5876. .stateEffect(true)
  5877. .margin({ right: 20, bottom: 20 })
  5878. .onClick(async () => {
  5879. this.doEdit(item)
  5880. })
  5881. Button('取消')
  5882. .fontColor(Color.White)
  5883. .layoutWeight(1)
  5884. .height(50)
  5885. .width(100)
  5886. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5887. .backgroundColor(this.themeColor)
  5888. .stateEffect(true)
  5889. .margin({ left: 20, bottom: 20 })
  5890. .onClick(async () => {
  5891. if(this.isGridMusic){
  5892. this.longItemFilePath =''
  5893. }else{
  5894. this.isShowEdit = false
  5895. }
  5896. this.setEditStrEmpty()
  5897. if(this.isShowPlay){
  5898. this.isShowEdit = false
  5899. }
  5900. })
  5901. }
  5902. .margin({
  5903. left: 38,
  5904. right: 38,
  5905. top: 10,
  5906. bottom: 10
  5907. })
  5908. .width(250)
  5909. .height(60)
  5910. }
  5911. }
  5912. .margin({ bottom: 20 })
  5913. }
  5914. setEditStrEmpty(){
  5915. this.imagePathStr = ''
  5916. this.lyricConStr = ''
  5917. this.artistStr = ''
  5918. this.titleStr = ''
  5919. this.ablumStr = ''
  5920. this.genreStr = ''
  5921. this.yearStr = ''
  5922. this.trackStr = ''
  5923. this.albumArtistStr = ''
  5924. this.composerStr = ''
  5925. this.lyricistStr = ''
  5926. this.commentStr = ''
  5927. this.discStr = ''
  5928. }
  5929. @Builder
  5930. detailSheet(item:VideoItem) {
  5931. Scroll() {
  5932. Column() {
  5933. this.songDetail(item)
  5934. }
  5935. }
  5936. .width('100%')
  5937. .height('100%')
  5938. }
  5939. @Builder
  5940. songDetail(currentItem:VideoItem) {
  5941. Column() {
  5942. if (currentItem) {
  5943. Row() {
  5944. Stack() {
  5945. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  5946. currentItem.pixelMapPath)
  5947. .fillColor(this.themeColor)
  5948. .height(80)
  5949. .width(80)
  5950. .borderRadius(10)
  5951. .opacity(this.opacityItem)// 绑定透明度
  5952. .margin({ left: 22 })
  5953. }
  5954. Column() {
  5955. Column() {
  5956. Text(currentItem.name)
  5957. .fontSize(16)
  5958. .maxLines(1)
  5959. .animation({
  5960. duration: 555,
  5961. curve: 'Linear',
  5962. })
  5963. .fontColor($r('app.color.text_color'))
  5964. .margin({ left: 15 })
  5965. }
  5966. .height('100%')
  5967. .width('100%')
  5968. .justifyContent(FlexAlign.Center)
  5969. .alignItems(HorizontalAlign.Start)
  5970. }
  5971. .height('100%')
  5972. }
  5973. .width('100%')
  5974. .height(90)
  5975. .justifyContent(FlexAlign.SpaceBetween)
  5976. Row() {
  5977. Text('艺术家:')
  5978. .fontSize(14)
  5979. .fontColor($r('app.color.text_color'))
  5980. .margin({ left: 22 })
  5981. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  5982. .fontSize(14)
  5983. .fontColor($r('app.color.text_color'))
  5984. .margin({ left: 10 })
  5985. .layoutWeight(1)
  5986. }
  5987. .width('100%')
  5988. .margin({ top: 10, bottom: 10 })
  5989. .justifyContent(FlexAlign.Start)
  5990. Row() {
  5991. Text('专辑名:')
  5992. .fontSize(14)
  5993. .fontColor($r('app.color.text_color'))
  5994. .margin({ left: 22 })
  5995. Text(currentItem?.album ?currentItem.album : '未知专辑')
  5996. .fontSize(14)
  5997. .margin({ left: 10 })
  5998. .fontColor($r('app.color.text_color'))
  5999. .layoutWeight(1)
  6000. }
  6001. .width('100%')
  6002. .margin({ top: 10, bottom: 10 })
  6003. .justifyContent(FlexAlign.Start)
  6004. Row() {
  6005. Text('时长:')
  6006. .fontSize(14)
  6007. .fontColor($r('app.color.text_color'))
  6008. .margin({ left: 22 })
  6009. Text(StrUtil.isEmpty(currentItem.duration)?
  6010. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  6011. .fontSize(14)
  6012. .margin({ left: 10 })
  6013. .fontColor($r('app.color.text_color'))
  6014. .layoutWeight(1)
  6015. }
  6016. .width('100%')
  6017. .margin({ top: 10, bottom: 10 })
  6018. .justifyContent(FlexAlign.Start)
  6019. Row() {
  6020. Text('采样率:')
  6021. .fontSize(14)
  6022. .fontColor($r('app.color.text_color'))
  6023. .margin({ left: 22 })
  6024. Text(Utility.convertToKHz(currentItem.sampleRate))
  6025. .fontSize(14)
  6026. .margin({ left: 10 })
  6027. .fontColor($r('app.color.text_color'))
  6028. .layoutWeight(1)
  6029. }
  6030. .width('100%')
  6031. .margin({ top: 10, bottom: 10 })
  6032. .justifyContent(FlexAlign.Start)
  6033. Row() {
  6034. Text('比特率:')
  6035. .fontSize(14)
  6036. .fontColor($r('app.color.text_color'))
  6037. .margin({ left: 22 })
  6038. Text(currentItem.bit_rate)
  6039. .fontSize(14)
  6040. .margin({ left: 10 })
  6041. .fontColor($r('app.color.text_color'))
  6042. .layoutWeight(1)
  6043. }
  6044. .width('100%')
  6045. .margin({ top: 10, bottom: 10 })
  6046. .justifyContent(FlexAlign.Start)
  6047. Row() {
  6048. Text('位深:')
  6049. .fontSize(14)
  6050. .fontColor($r('app.color.text_color'))
  6051. .margin({ left: 22 })
  6052. Text(`${currentItem.bits_per_raw_sample} bits`)
  6053. .fontSize(14)
  6054. .margin({ left: 10 })
  6055. .fontColor($r('app.color.text_color'))
  6056. .layoutWeight(1)
  6057. }
  6058. .width('100%')
  6059. .margin({ top: 10, bottom: 10 })
  6060. .justifyContent(FlexAlign.Start)
  6061. Row() {
  6062. Text('声道:')
  6063. .fontSize(14)
  6064. .fontColor($r('app.color.text_color'))
  6065. .margin({ left: 22 })
  6066. Text(`${currentItem.channels}`)
  6067. .fontSize(14)
  6068. .margin({ left: 10 })
  6069. .fontColor($r('app.color.text_color'))
  6070. .layoutWeight(1)
  6071. }
  6072. .width('100%')
  6073. .margin({ top: 10, bottom: 10 })
  6074. .justifyContent(FlexAlign.Start)
  6075. Row() {
  6076. Text('声道布局:')
  6077. .fontSize(14)
  6078. .fontColor($r('app.color.text_color'))
  6079. .margin({ left: 22 })
  6080. Text(`${currentItem.channel_layout}`)
  6081. .fontSize(14)
  6082. .margin({ left: 10 })
  6083. .fontColor($r('app.color.text_color'))
  6084. .layoutWeight(1)
  6085. }
  6086. .width('100%')
  6087. .margin({ top: 10, bottom: 10 })
  6088. .justifyContent(FlexAlign.Start)
  6089. Row() {
  6090. Text('起始播放点:')
  6091. .fontSize(14)
  6092. .fontColor($r('app.color.text_color'))
  6093. .margin({ left: 22 })
  6094. Text(`${currentItem.start_time}`)
  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(currentItem.genre)
  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.year)
  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.probe_score+"")
  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.track)
  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.disc)
  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.ALBUMARTIST)
  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.COMPOSER)
  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.LYRICIST)
  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.COMMENT)
  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(Utility.formatMimeType(currentItem.mimeType))
  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.playCount?.toString())
  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.nb_streams?.toString())
  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.size)
  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.fileName)
  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.cTime)
  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(currentItem.filePath)
  6319. .fontSize(12)
  6320. .margin({ left: 10 })
  6321. .fontColor($r('app.color.text_color'))
  6322. .layoutWeight(1)
  6323. }
  6324. .margin({ top: 10, bottom: 10 })
  6325. .width('100%')
  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.lyricContent)
  6333. .fontSize(12)
  6334. .copyOption(CopyOptions.InApp)
  6335. .margin({ left: 10 })
  6336. .fontColor($r('app.color.text_color'))
  6337. .layoutWeight(1)
  6338. }
  6339. .margin({ top: 10, bottom: 10 })
  6340. .width('100%')
  6341. .justifyContent(FlexAlign.Start)
  6342. }
  6343. }
  6344. .margin({ bottom: 20 })
  6345. }
  6346. //定时关闭布局
  6347. @Builder
  6348. TimeCloseSheet() {
  6349. Scroll() {
  6350. Column() {
  6351. this.TimeClose()
  6352. }
  6353. }
  6354. .width('100%')
  6355. .height('100%')
  6356. }
  6357. //倒计时关闭音乐,退出App功能实现。
  6358. @State selectedMinutes: number = 0 // 0表示未开启
  6359. @State remainingSeconds: number = 0
  6360. // 预设时间选项
  6361. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  6362. private formatTime(seconds: number): string {
  6363. const mins = Math.floor(seconds / 60)
  6364. const secs = seconds % 60
  6365. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  6366. }
  6367. // 开始倒计时
  6368. private handleTimeSelect(minutes: number) {
  6369. if (minutes === this.selectedMinutes) {
  6370. this.stopCountdown();
  6371. this.selectedMinutes = 0;
  6372. return;
  6373. }
  6374. this.selectedMinutes = minutes;
  6375. this.remainingSeconds = minutes * 60;
  6376. this.startCountdown(); // 新增调用
  6377. }
  6378. @Builder
  6379. TimeClose() {
  6380. Column() {
  6381. // 倒计时显示区域
  6382. Text(this.selectedMinutes > 0 ?
  6383. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  6384. "定时关闭未开启")
  6385. .fontSize(17)
  6386. .fontColor($r('app.color.text_color'))
  6387. .margin({ top: 2, bottom: 8 });
  6388. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6389. ForEach(this.presetTimes, (minutes: number, index: number) => {
  6390. // 单行时间选项容器
  6391. Row() {
  6392. // 文字描述区域
  6393. Text(this.getDisplayText(minutes))
  6394. .fontSize(15)
  6395. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  6396. $r('app.color.text_color'))// 选中态颜色变化
  6397. .textAlign(TextAlign.Start)
  6398. .layoutWeight(1); // 占据剩余空间
  6399. // 复选框样式的选择器
  6400. Row() {
  6401. if (minutes === this.selectedMinutes) {
  6402. // 选中状态 - 带勾号的圆形复选框
  6403. Row() {
  6404. // 使用系统内置的勾号图标
  6405. Image($r('sys.media.ohos_ic_public_ok'))
  6406. .width(14)
  6407. .height(14)
  6408. .fillColor(Color.White)
  6409. }
  6410. .width(24)
  6411. .height(24)
  6412. .borderRadius(12)
  6413. .backgroundColor(this.themeColor)
  6414. .justifyContent(FlexAlign.Center)
  6415. .alignItems(VerticalAlign.Center)
  6416. } else {
  6417. // 未选中状态的圆形边框
  6418. Row()
  6419. .width(24)
  6420. .height(24)
  6421. .borderRadius(12)
  6422. .border({
  6423. width: 2,
  6424. color: $r('app.color.text_color'),
  6425. style: BorderStyle.Solid
  6426. })
  6427. .backgroundColor(Color.Transparent)
  6428. }
  6429. }
  6430. .width(24)
  6431. .height(24)
  6432. .margin({ left: 20 })
  6433. .justifyContent(FlexAlign.Center)
  6434. .alignItems(VerticalAlign.Center)
  6435. }
  6436. .width('100%')
  6437. .padding({
  6438. top: 18,
  6439. bottom: 18,
  6440. left: 18,
  6441. right: 18
  6442. })
  6443. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  6444. $r('app.color.bottom_control_background')) // 选中背景高亮
  6445. .borderRadius(12)
  6446. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6447. .margin({ bottom: 18 })
  6448. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  6449. });
  6450. }
  6451. .width('100%')
  6452. .padding(16)
  6453. }
  6454. }
  6455. // 获取显示文本
  6456. private getDisplayText(minutes: number): string {
  6457. if (minutes === -1) {
  6458. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  6459. }
  6460. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  6461. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  6462. }
  6463. // 处理选择事件
  6464. private handleSelect(minutes: number): void {
  6465. if (minutes === -1) { // 自定义
  6466. // 弹出自定义时间对话框
  6467. DialogHelper.showTextInputDialog({
  6468. title: '自定义时间',
  6469. maskColor: Color.Transparent,
  6470. inputType: InputType.Number,
  6471. text: '',
  6472. onChange: (text) => {
  6473. console.error("onChange: " + text);
  6474. },
  6475. onAction: (action, dialogId, content) => {
  6476. if (action == DialogAction.TWO) {
  6477. const customMinutes = Number(content);
  6478. if (customMinutes > 0) {
  6479. this.handleTimeSelect(customMinutes); // 设置自定义时间
  6480. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  6481. }
  6482. }
  6483. }
  6484. });
  6485. } else {
  6486. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  6487. }
  6488. }
  6489. // 添加定时器引用
  6490. private timerId: number = -1;
  6491. // 启动/重置倒计时
  6492. private startCountdown() {
  6493. // 清除旧定时器
  6494. if (this.timerId !== -1) {
  6495. clearInterval(this.timerId);
  6496. }
  6497. // 创建新定时器
  6498. if (this.selectedMinutes > 0) {
  6499. this.timerId = setInterval(() => {
  6500. if (this.remainingSeconds === 15) {
  6501. this.showConfirmationDialog();
  6502. }
  6503. if (this.remainingSeconds > 0) {
  6504. this.remainingSeconds -= 1;
  6505. } else {
  6506. this.stopCountdown();
  6507. this.handleTimeout();
  6508. }
  6509. }, 1000);
  6510. }
  6511. }
  6512. // 15倒计时后再次提示显示确认是否关闭App对话框
  6513. private showConfirmationDialog() {
  6514. DialogHelper.showAlertDialog({
  6515. backgroundColor: $r('app.color.btn_green'),
  6516. title: '确认关闭',
  6517. maskColor: Color.Transparent,
  6518. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  6519. borderStyle: BorderStyle.Dashed,
  6520. primaryButton: '暂不关闭',
  6521. secondaryButton: '确定',
  6522. onAction: (action) => {
  6523. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  6524. this.stopCountdown();
  6525. this.selectedMinutes = 0
  6526. } else if (action == DialogAction.TWO) {
  6527. }
  6528. }
  6529. })
  6530. }
  6531. // 停止倒计时
  6532. private stopCountdown() {
  6533. if (this.timerId !== -1) {
  6534. clearInterval(this.timerId);
  6535. this.timerId = -1;
  6536. }
  6537. }
  6538. // 超时处理
  6539. private handleTimeout() {
  6540. // 执行播放器关闭逻辑
  6541. this.selectedMinutes = 0;
  6542. ToastUtil.showToast(" 定时关闭已完成");
  6543. this.stop(); // 假设存在的播放器实例
  6544. //退出APP
  6545. const mContext = getContext(this) as common.UIAbilityContext
  6546. mContext.terminateSelf();
  6547. AvSessionController.getInstance(true).unregisterSessionListener()
  6548. }
  6549. //倒计时关闭音乐,退出App功能实现结束。
  6550. //播放列表的拖动List 重新排序
  6551. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  6552. //左滑操作 移动文件 重命名 删除等操作
  6553. @Builder
  6554. sonButton(item: VideoItem, index: number, filePath: string) {
  6555. Row() {
  6556. //加入下一首播放
  6557. Button() {
  6558. Image($r('app.media.next_to_play'))
  6559. .fillColor(Color.White)
  6560. .width(20)
  6561. }
  6562. .width(40)
  6563. .height(40)
  6564. .type(ButtonType.Circle)
  6565. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6566. .backgroundColor(this.themeColor)
  6567. .margin(5)
  6568. .onClick(() => {
  6569. this.addToNextPlay(item);
  6570. })
  6571. Button() {
  6572. Image($r('app.media.close'))
  6573. .fillColor(Color.White)
  6574. .width(20)
  6575. }
  6576. .width(40)
  6577. .height(40)
  6578. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6579. .type(ButtonType.Circle)
  6580. .backgroundColor(this.themeColor)
  6581. .margin(5)
  6582. .onClick(() => {
  6583. this.songList.splice(Number(index), 1)
  6584. this.sonDataSource.pushArrayData(this.songList)
  6585. })
  6586. Button() {
  6587. Image($r('app.media.share2'))
  6588. .fillColor(Color.White)
  6589. .width(20)
  6590. }
  6591. .width(40)
  6592. .height(40)
  6593. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6594. .type(ButtonType.Circle)
  6595. .backgroundColor(this.themeColor)
  6596. .margin(5)
  6597. .onClick(() => {
  6598. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6599. })
  6600. }
  6601. }
  6602. itemMoveSon(index: number, newIndex: number): void {
  6603. if (newIndex < 0 || newIndex >= this.songList.length) {
  6604. return;
  6605. }
  6606. let tmp = this.songList.splice(index, 1);
  6607. this.songList.splice(newIndex, 0, tmp[0]);
  6608. this.sonDataSource.pushArrayData(this.songList)
  6609. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  6610. }
  6611. @Builder
  6612. PlayList() {
  6613. List({ scroller: this.playListScroller }) {
  6614. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  6615. ListItem() {
  6616. this.MusicItemSon(item, index)
  6617. }
  6618. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  6619. .animation({
  6620. duration: 666,
  6621. curve: 'ease-in-out' // 可选动画曲线
  6622. })
  6623. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  6624. TransitionEffect.scale({ x: 0, y: 0 })))
  6625. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6626. //拖动List关键代码开始
  6627. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  6628. .zIndex(this.dragItem === index ? 1 : 0)
  6629. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  6630. .gesture(
  6631. GestureGroup(GestureMode.Sequence,
  6632. LongPressGesture({ repeat: true })
  6633. .onAction((event?: GestureEvent) => {
  6634. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6635. this.scaleItem = index
  6636. })
  6637. })
  6638. .onActionEnd(() => {
  6639. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6640. this.scaleItem = -1
  6641. })
  6642. }),
  6643. PanGesture({ fingers: 1, direction: null, distance: 0 })
  6644. .onActionStart(() => {
  6645. this.dragItem = index // 记录当前拖动项索引
  6646. this.dragRefOffset = 0 // 重置偏移基准
  6647. })
  6648. .onActionUpdate((event: GestureEvent) => {
  6649. this.offsetY = event.offsetY - this.dragRefOffset;
  6650. this.neighborItem = -1;
  6651. let indexA = this.songList.indexOf(item);
  6652. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6653. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6654. let value: number = 0;
  6655. if (this.offsetY < 0) {
  6656. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6657. this.neighborItem = indexA - 1;
  6658. this.neighborScale = 1 - value / 20;
  6659. } else if (this.offsetY > 0) {
  6660. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6661. this.neighborItem = indexA + 1;
  6662. this.neighborScale = 1 - value / 20;
  6663. }
  6664. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  6665. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6666. this.offsetY -= this.ITEM_INTV;
  6667. this.dragRefOffset += this.ITEM_INTV;
  6668. this.itemMoveSon(indexA, indexA + 1);
  6669. });
  6670. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6671. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6672. this.offsetY += this.ITEM_INTV;
  6673. this.dragRefOffset -= this.ITEM_INTV;
  6674. this.itemMoveSon(indexA, indexA - 1);
  6675. });
  6676. }
  6677. })
  6678. .onActionEnd((event: GestureEvent) => {
  6679. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6680. this.dragItem = -1
  6681. this.neighborItem = -1
  6682. })
  6683. animateTo({
  6684. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6685. }, () => {
  6686. this.scaleItem = -1
  6687. })
  6688. })
  6689. )
  6690. .onCancel(() => {
  6691. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6692. this.dragItem = -1
  6693. this.neighborItem = -1
  6694. })
  6695. animateTo({
  6696. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6697. }, () => {
  6698. this.scaleItem = -1
  6699. })
  6700. })
  6701. ) //拖动List关键代码结束
  6702. .onClick(() => {
  6703. this.doPlay(item, index, true)
  6704. })
  6705. }, (item: VideoItem) => item.filePath)
  6706. }
  6707. .width('100%')
  6708. .height('100%')
  6709. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  6710. // .animation({ duration: 500, curve: Curve.Ease }))
  6711. .cachedCount(10)
  6712. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6713. .gesture(PinchGesture({ fingers: 2 })
  6714. .onActionEnd((event: GestureEvent) => {
  6715. this.setSonListTwoFingers()
  6716. })
  6717. .onActionUpdate(e => {
  6718. this.scaleValue = this.pinchValue * e.scale
  6719. })
  6720. .onActionStart(e => {
  6721. }))
  6722. .padding({
  6723. bottom: 0
  6724. })
  6725. }
  6726. setSonListTwoFingers() {
  6727. this.pinchValue = this.scaleValue;
  6728. Logger.info('this.pinchValue = ' + this.pinchValue);
  6729. if (this.pinchValue >= 1) {
  6730. this.sonTwoFingerType++
  6731. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  6732. if (this.sonTwoFingerType > 3) {
  6733. this.sonTwoFingerType = 1
  6734. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6735. }
  6736. } else {
  6737. this.sonTwoFingerType--
  6738. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  6739. if (this.sonTwoFingerType < 1) {
  6740. this.sonTwoFingerType = 1
  6741. }
  6742. }
  6743. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  6744. this.pinchValue = 1;
  6745. this.scaleValue = 1;
  6746. }
  6747. @State sonTwoFingerType:number = 3
  6748. @Builder
  6749. private MusicItemSon(item: VideoItem, index?: number) {
  6750. Button({ type: ButtonType.Normal, stateEffect: true }) {
  6751. Row() {
  6752. Stack() {
  6753. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  6754. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6755. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6756. .alt($r('app.media.music_red'))
  6757. .fillColor(this.themeColor)
  6758. .borderRadius('100%')
  6759. .clip(true)
  6760. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  6761. .draggable(false)// 禁止长按手势拖动
  6762. .autoResize(true) // 重采样,可减少内存占用
  6763. .margin({ left: 20 })
  6764. }
  6765. .width('15%')
  6766. Column() {
  6767. Column() {
  6768. Text(this.isShowFileName?item.fileName :item.name)
  6769. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  6770. .fontColor(this.curIndex === index ? this.themeColor :
  6771. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  6772. .maxLines(1)
  6773. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  6774. Row() {
  6775. Column(){
  6776. Text(item.md5Str?.includes('Lossless')?
  6777. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6778. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  6779. .padding({ top: 3,right:6,left:6,bottom:3 })
  6780. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6781. $r('app.color.text_color'))
  6782. .fontWeight(500)
  6783. .borderRadius(12)
  6784. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  6785. .backgroundColor('#FFC107')
  6786. }
  6787. .padding({ top: 8 })
  6788. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  6789. item.artist + ' ' + item?.duration)
  6790. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6791. .padding({ top: 8 })
  6792. .maxLines(1)
  6793. .fontColor(this.curIndex === index ? this.themeColor :
  6794. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6795. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  6796. Blank()
  6797. Text(item.size)
  6798. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6799. .padding({ top: 8 })
  6800. .maxLines(1)
  6801. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  6802. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  6803. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6804. .margin({ left: 10 })
  6805. }
  6806. }
  6807. .height('100%')
  6808. .width('100%')
  6809. .justifyContent(FlexAlign.Center)
  6810. .alignItems(HorizontalAlign.Start)
  6811. }
  6812. .height('100%')
  6813. .width('65%')
  6814. Column() {
  6815. ImageAnimator()
  6816. .images(this.imagesF)// 动画数组
  6817. .duration(1000)// 持续
  6818. .state(this.animationState)// 动画状态
  6819. .fillMode(FillMode.Forwards)
  6820. .width(18)
  6821. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  6822. Visibility.None)
  6823. .height(18)
  6824. .iterations(-1) // 播放次数
  6825. }
  6826. .width('20%')
  6827. }
  6828. }
  6829. .backgroundColor(Color.Transparent)
  6830. .width('100%')
  6831. .reuseId('son_item')
  6832. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  6833. .shadow(this.scaleItem === index ? {
  6834. radius: 70,
  6835. color: '#15000000',
  6836. offsetX: 0,
  6837. offsetY: 0
  6838. } :
  6839. {
  6840. radius: 0,
  6841. color: '#15000000',
  6842. offsetX: 0,
  6843. offsetY: 0
  6844. })
  6845. .animation({ curve: Curve.Sharp, duration: 300 })
  6846. }
  6847. @Builder
  6848. MusicPlayBuilder() {
  6849. Column() {
  6850. this.IjkMusicPlayerView()
  6851. }
  6852. .height('100%')
  6853. .width('100%')
  6854. .onDisAppear(() => {
  6855. this.translateY = 0;
  6856. })
  6857. .translate({ y: this.translateY })
  6858. .gesture(
  6859. PanGesture(this.panOption)
  6860. .onActionUpdate((event?: GestureEvent) => {
  6861. if (event) {
  6862. // 只允许向下滑动,向上滑动时限制为0
  6863. this.translateY = Math.max(0, event.offsetY);
  6864. }
  6865. })
  6866. .onActionEnd((event?: GestureEvent) => {
  6867. // 使用更低的阈值和滑动速度判断
  6868. const minDistance = 100; // 最小滑动距离 100vp
  6869. const minVelocity = 500; // 最小滑动速度
  6870. // 获取滑动速度(如果可用)
  6871. const velocity = event?.velocityY || 0;
  6872. // 判断是否应该关闭:距离足够 或者 速度足够快
  6873. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  6874. if (shouldClose) {
  6875. // 添加关闭动画
  6876. this.getUIContext().animateTo({
  6877. duration: 300,
  6878. curve: Curve.Smooth
  6879. }, () => {
  6880. this.isShowPlay = false;
  6881. this.translateY = 0;
  6882. })
  6883. } else {
  6884. // 回弹动画
  6885. this.getUIContext().animateTo({
  6886. duration: 300,
  6887. curve: Curve.Smooth
  6888. }, () => {
  6889. this.translateY = 0;
  6890. })
  6891. }
  6892. })
  6893. )
  6894. }
  6895. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  6896. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  6897. HeightBreakpoint.HEIGHT_LG;
  6898. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  6899. @State topBarHeight: number = 50
  6900. @State barOpacity: number = 1
  6901. @State barBottomOpacity: number = 1
  6902. private hideDone: boolean = false;
  6903. @State currentYOffset: number = 0;
  6904. @State bottomBarHeight: number = 55;
  6905. private isHiding: boolean = false;
  6906. //是否是Pura X外屏,或者小屏幕
  6907. isPuraWP() {
  6908. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6909. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  6910. }
  6911. //是否是Pura X外屏,或者小屏幕,手机横屏
  6912. /**
  6913. * 是否是Pura X外屏,或者小屏幕,手机横屏
  6914. * @returns
  6915. */
  6916. isCoverOpacity() {
  6917. if (this.isPuraWP()) {
  6918. return true
  6919. }
  6920. if (this.isPhoneLan()) {
  6921. return true
  6922. }
  6923. if (deviceInfo.marketName.includes('Pura X')
  6924. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  6925. return true
  6926. }
  6927. return false
  6928. }
  6929. //是不是手机横屏
  6930. isPhoneLan() {
  6931. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  6932. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  6933. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  6934. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  6935. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  6936. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  6937. if (this.isHiCarKuanBianPing()) {
  6938. return true
  6939. }
  6940. if (this.isHiCar()) {
  6941. return false
  6942. }
  6943. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6944. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  6945. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  6946. return true
  6947. }
  6948. return false
  6949. }
  6950. //是不是1920x720的hicar的屏幕分辨率
  6951. isHiCarKuanBianPing(){
  6952. if(!this.isHiCar()){
  6953. return false
  6954. }
  6955. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6956. { ratio: 1920 / 720, name: "1920x720" },
  6957. ];
  6958. const currentRatio: number = this.windowWidth / this.windowHeight;
  6959. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6960. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  6961. for (const hiCarRatio of hiCarAspectRatios) {
  6962. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  6963. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6964. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6965. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6966. //宽扁平的尺寸设置列表展示
  6967. this.twoFingerType ==3
  6968. this.isGridMusic = false
  6969. return true;
  6970. }
  6971. }
  6972. return false;
  6973. }
  6974. //是不是hicar的屏幕分辨率
  6975. isHiCarSmall() {
  6976. if(!this.isHiCar()){
  6977. return false
  6978. }
  6979. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  6980. {
  6981. this.columns = 6
  6982. return false
  6983. }
  6984. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6985. { ratio: 800 / 480, name: "800x480" },
  6986. { ratio: 1280 / 720, name: "1280x720" },
  6987. { ratio: 1920 / 1080, name: "1920x1080" },
  6988. ];
  6989. const currentRatio: number = this.windowWidth / this.windowHeight;
  6990. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6991. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  6992. for (const hiCarRatio of hiCarAspectRatios) {
  6993. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  6994. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6995. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  6996. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6997. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6998. //宽扁平的尺寸设置列表展示
  6999. return true;
  7000. }
  7001. }
  7002. return false;
  7003. }
  7004. isHiCar() {
  7005. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  7006. }
  7007. //是不是正常的手机竖屏
  7008. isPhonePortrait() {
  7009. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  7010. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  7011. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  7012. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7013. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  7014. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  7015. return true
  7016. }
  7017. return false
  7018. }
  7019. @State showSpeedDialog: boolean = false
  7020. @State longPressSpeed: number = 3 //长按默认倍数
  7021. @Builder
  7022. SpeedDialog() {
  7023. Stack() {
  7024. Column() {
  7025. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7026. .fontColor(Color.White)
  7027. .visibility(Visibility.Hidden)
  7028. }
  7029. .backgroundColor(Color.Black)
  7030. .borderRadius(20)
  7031. .padding({
  7032. top: 10,
  7033. right: 20,
  7034. left: 15,
  7035. bottom: 20
  7036. })
  7037. .opacity(0.6)
  7038. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7039. .fontColor(Color.White)
  7040. }
  7041. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  7042. .zIndex(5)
  7043. .margin({ top: 80 })
  7044. }
  7045. @Builder
  7046. IjkMusicPlayerView() {
  7047. Column() {
  7048. Column() {
  7049. Column() {
  7050. //播放标题
  7051. Column() {
  7052. this.PlayTitle()
  7053. }
  7054. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  7055. .width('100%')
  7056. .margin({ top: 0 })
  7057. .height(PlayConstants.HEIGHT)
  7058. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  7059. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  7060. if (this.showSpeedDialog) {
  7061. this.SpeedDialog()
  7062. }
  7063. Stack() {
  7064. //手势拖动快进
  7065. Column()
  7066. .width(CommonConstants.FULL_PERCENT)
  7067. .height('100%')
  7068. .gesture(
  7069. GestureGroup(GestureMode.Parallel,
  7070. // 长按屏幕倍数播放
  7071. LongPressGesture({ repeat: true })
  7072. .onAction(() => {
  7073. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7074. this.showSpeedDialog = true;
  7075. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  7076. }
  7077. })
  7078. .onActionEnd(() => {
  7079. this.showSpeedDialog = false;
  7080. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7081. }),
  7082. //双击屏幕暂停或者播放
  7083. TapGesture({ count: 2 })
  7084. .onAction((event: GestureEvent) => {
  7085. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7086. ToastUtil.showToast('已暂停')
  7087. }
  7088. console.info('onecold playOrPause 6693')
  7089. this.playOrPause()
  7090. })
  7091. )
  7092. )
  7093. }
  7094. .height('65%')
  7095. Swiper() {
  7096. this.CoverInfo()
  7097. this.PlayerLyrics()
  7098. }
  7099. .onChange((index: number) => {
  7100. this.currentSwiperIndex = index
  7101. })
  7102. .indicator(false)
  7103. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  7104. // new DotIndicator()
  7105. // .top(this.isCoverOpacity()?0:10)
  7106. //
  7107. // .selectedColor($r('app.color.select_swiper'))
  7108. // .color($r('app.color.slider_track')):false
  7109. // )
  7110. .displayCount(new BreakpointType({
  7111. sm: 1,
  7112. md: 2,
  7113. lg: 2,
  7114. xl: 2,
  7115. xxl: 2
  7116. }).getValue(this.currentBreakpoint))
  7117. .clip(false)
  7118. .loop(false)
  7119. .autoPlay(false)
  7120. // .interval(8000)
  7121. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  7122. .height('100%')
  7123. .hitTestBehavior(HitTestMode.Transparent)
  7124. Image($r('app.media.icon_replay'))
  7125. .objectFit(ImageFit.Auto)
  7126. .width('120px')
  7127. .height('120px')
  7128. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  7129. .border({ width: 0 })
  7130. .visibility(Visibility.None)
  7131. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  7132. .onClick(() => {
  7133. console.info('onecold startPlayOrResumePlay 6744')
  7134. this.startPlayOrResumePlay();
  7135. })
  7136. }
  7137. .width(CommonConstants.FULL_PERCENT)
  7138. .height(CommonConstants.FULL_PERCENT)
  7139. .justifyContent(FlexAlign.End)
  7140. }
  7141. .justifyContent(FlexAlign.End)
  7142. .margin({ bottom: 8 })
  7143. }
  7144. .backgroundImage(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7145. // .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  7146. // (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  7147. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  7148. // .backgroundImagePosition(Alignment.Center)
  7149. .animation({
  7150. duration: 666,
  7151. curve: 'ease-in-out' // 可选动画曲线
  7152. })
  7153. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  7154. BlurStyle.BACKGROUND_ULTRA_THICK)
  7155. .hitTestBehavior(HitTestMode.Transparent)
  7156. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  7157. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  7158. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  7159. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  7160. .onClick(() => {
  7161. // this.startAutoHide()
  7162. if(this.isHiCar())
  7163. return
  7164. if(this.is_auto_hide_progress){
  7165. this.is_auto_hide_progress = false
  7166. }
  7167. this.startAutoHide()
  7168. })
  7169. }
  7170. @State progressValue: number = 0;
  7171. @State currentTime: string = "00:00";
  7172. @State totalTime: string = "00:00";
  7173. @State loadingVisible: Visibility = Visibility.None;
  7174. @State replayVisible: Visibility = Visibility.None;
  7175. @State slideEnable: boolean = false;
  7176. @State aspRatio: number = 0.5;
  7177. @State mContext: object | undefined = undefined;
  7178. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  7179. @State mFirst: boolean = true;
  7180. @State mDestroyPage: boolean = false;
  7181. @State playSpeed: number = 1;
  7182. @State oldSeconds: number = 0;
  7183. @State isSeekTo: boolean = false;
  7184. @State isCurrentTime: boolean = false;
  7185. @State videoWidth: string = '100%';
  7186. @State videoHeight: string = '100%';
  7187. @State initAspectRatio: number = 1;
  7188. @State videoAspectRatio: number = this.initAspectRatio;
  7189. private videoUrl: string = '';
  7190. private last: number = 0;
  7191. @State videoParentAspectRatio: number = this.initAspectRatio;
  7192. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  7193. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  7194. @State PROGRESS_MAX_VALUE: number = 100;
  7195. @State updateProgressTimer: number = 0;
  7196. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  7197. @State name: string = '';
  7198. // @State loop: boolean = false;
  7199. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  7200. @State multiple: string = '1.0X';
  7201. xcomponentController: XComponentController = new XComponentController()
  7202. private panOptionBright: PanGestureOptions =
  7203. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  7204. private panOptionVolume: PanGestureOptions =
  7205. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  7206. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  7207. //手势的音量控制和亮度控制
  7208. private positionX: number = PlayConstants.POSITION_X;
  7209. private positionY: number = PlayConstants.POSITION_Y;
  7210. private windowClass: window.Window = globalThis.windowClass
  7211. @State volume: number = 0.5;
  7212. @State volumeSmall: boolean = false
  7213. @State autoParseMusicName: boolean = true
  7214. @State isShowFileName: boolean = false
  7215. @State isLongNameRoLL: boolean = true//长歌名滚动
  7216. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  7217. @State bright: number = PlayConstants.BRIGHT;
  7218. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  7219. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  7220. @State screenWidth: number = 0
  7221. @State screenHeight: number = 0
  7222. @State statusBarHeight: number = 0
  7223. @State isYesFull: boolean = false
  7224. private seekValue: number = 0
  7225. @State isVideoLock: boolean = false; // Whether the video playback is locked
  7226. eventHub = getContext().eventHub;
  7227. //投播组件
  7228. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  7229. private castController: avSession.AVCastController | undefined = undefined;
  7230. @State isCastPlaying: boolean = false;
  7231. @State currentTime2: number = 0;
  7232. @State currentStringTime: string = '00:00';
  7233. @State duration: number = 0;
  7234. @State isReady: boolean = false;
  7235. @State durationTime: number = 0;
  7236. @State durationStringTime: string = '00:00';
  7237. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  7238. // @State isPlaying: boolean = false;
  7239. private castSeek: boolean = false;
  7240. private castItem: avSession.AVQueueItem | undefined = undefined;
  7241. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  7242. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  7243. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  7244. @State rotateAngle2: number = -9
  7245. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  7246. @State cover: string | undefined = '';
  7247. @State artist: string | undefined = ''
  7248. // 1.初始化controller
  7249. private lyricController: LyricController = new LyricController()
  7250. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  7251. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  7252. private parser = new LyricParser()
  7253. @State randomColor: string = 'rgb(0,0,0)'
  7254. @State randomShakenX: number = 0
  7255. @State randomShakenY: number = 0
  7256. @State lyricTextSize: number = 24
  7257. @State lyricContent: string = ''
  7258. @State isDebug: boolean = false
  7259. @State isHightLightCenter: boolean = true
  7260. /**
  7261. * 初始化歌词加载与展示逻辑
  7262. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  7263. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  7264. * @param isApi2 是否使用API2获取歌词(可选)
  7265. *
  7266. * 主要流程:
  7267. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  7268. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  7269. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  7270. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  7271. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  7272. * 6. 解析失败或读取失败时,清空歌词显示。
  7273. *
  7274. * 注意事项:
  7275. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  7276. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  7277. * - 歌词内容解析后通过lyricController驱动UI渲染。
  7278. */
  7279. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  7280. if (StrUtil.isEmpty(lyricPath)) {
  7281. return
  7282. }
  7283. this.initPipLyricSetting()
  7284. this.lyricControllerSingle
  7285. .setTextSize(15)
  7286. .setCacheSize(4)
  7287. .setTextColor("#FFFFFF")
  7288. .setHighlightColor("#FFFFFF")
  7289. .setHighlightScale(1.2)
  7290. .setEmptyHint("")
  7291. .setAlignMode('center')
  7292. .setAnimationDuration(500)
  7293. .setSingleLine(true)
  7294. this.lyricContent = ''
  7295. this.lyricController
  7296. .setTextSize(this.currentLyricSize)
  7297. .setCacheSize(4)
  7298. .setTextColor("#DDDDDD")
  7299. .setHighlightColor("#FFFFFF")
  7300. .setEmptyHint("")
  7301. .setAnimationDuration(1000)
  7302. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  7303. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  7304. this.setBlurDegree(this.blurDegree, false)
  7305. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  7306. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  7307. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  7308. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  7309. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  7310. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  7311. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  7312. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7313. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  7314. this.lyricController.setTextWeight(this.lyricTextWeight)
  7315. this.showSingleLyric = false
  7316. this.timeOffset = 0
  7317. this.lyricController.setLyric(null)
  7318. this.lyricControllerSingle.setLyric(null)
  7319. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  7320. console.log("onecold lyricPath =" + lyricPath)
  7321. let neiqianLrc = ''
  7322. let lyContent = this.currentSong?.lyricContent
  7323. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  7324. neiqianLrc = lyContent
  7325. }
  7326. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  7327. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  7328. //赋值给this.lyricContent,播控中心才可以显示歌词
  7329. this.lyricContent = neiqianLrc
  7330. // 将文件内容按行分割成字符串数组
  7331. let lines = neiqianLrc.split('\n').map(line => line.trim());
  7332. // 3.解析歌词
  7333. let lyric = this.parser.parse(lines);
  7334. // 4.设置歌词
  7335. this.lyricController.setLyric(lyric);
  7336. this.lyricControllerXF.setLyric(lyric)
  7337. this.lyricControllerSingle.setLyric(lyric)
  7338. return
  7339. }
  7340. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  7341. && !Utility.isVideoByExtension(this.videoUrl))) {
  7342. if (this.currentSong !== undefined) {
  7343. // ToastUtil.showShort('正在为你搜索在线歌词!')
  7344. //判断是不是赞助会员,是会员的话才开启歌词功能
  7345. // if (!this.isDebug) {
  7346. // if (!Utility.isNoble()) {
  7347. // LogUtil.debug("onecold 不是赞助会员")
  7348. // return
  7349. // }
  7350. // if(!Utility.isPassInstallTime(33)){
  7351. // LogUtil.debug("onecold not pass time")
  7352. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  7353. // return
  7354. // }
  7355. // }
  7356. let artist = this.currentSong?.artist
  7357. if (artist === undefined) {
  7358. artist = ''
  7359. }
  7360. if (isApi2 === undefined) {
  7361. isApi2 = false
  7362. }
  7363. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  7364. // LogUtil.debug("onecold res =" + res)
  7365. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7366. if (StrUtil.isNotEmpty(res)) {
  7367. this.lyricContent = res
  7368. let lines = res.split('\n').map(line => line.trim());
  7369. // 3.解析歌词
  7370. let lyric = this.parser.parse(lines);
  7371. // 4.设置歌词
  7372. this.lyricController.setLyric(lyric);
  7373. this.lyricControllerXF.setLyric(lyric)
  7374. this.lyricControllerSingle.setLyric(lyric)
  7375. this.showSingleLyric = true
  7376. // 4.保存歌词文件lyric到本地
  7377. //2025年8月28日歌词不再加密下载
  7378. this.saveDataToFile(res, lyricPath, false)
  7379. } else {
  7380. this.lyricController.setLyric(null)
  7381. this.lyricControllerXF.setLyric(null)
  7382. this.lyricControllerSingle.setLyric(null)
  7383. if (isOnLineAndToast) {
  7384. ToastUtil.showShort('未获取到歌词!')
  7385. }
  7386. }
  7387. } else {
  7388. this.lyricController.setLyric(null)
  7389. this.lyricControllerXF.setLyric(null)
  7390. this.lyricControllerSingle.setLyric(null)
  7391. if (isOnLineAndToast) {
  7392. ToastUtil.showShort('未获取到歌词!')
  7393. }
  7394. }
  7395. })
  7396. } else {
  7397. this.lyricController.setLyric(null)
  7398. this.lyricControllerXF.setLyric(null)
  7399. this.lyricControllerSingle.setLyric(null)
  7400. if (isOnLineAndToast) {
  7401. ToastUtil.showShort('未获取到歌词!')
  7402. }
  7403. }
  7404. return
  7405. }
  7406. try {
  7407. let isJiaMi = false;
  7408. let realLyricPath = lyricPath
  7409. if (FileUtil.accessSync(jiaMilyricPath)) {
  7410. isJiaMi = true
  7411. realLyricPath = jiaMilyricPath
  7412. console.info("onecold 找到加密本地歌词 ");
  7413. } else {
  7414. isJiaMi = false
  7415. realLyricPath = lyricPath
  7416. console.info("onecold 找到本地歌词 ");
  7417. }
  7418. // 3.读取文件内容并指定编码为 UTF-8
  7419. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7420. const stat = await fileIo.stat(file.fd);
  7421. const arrayBuffer = new ArrayBuffer(stat.size);
  7422. fs.read(file.fd, arrayBuffer)
  7423. .then((readLen: number) => {
  7424. console.info("read file data succeed");
  7425. // let buf = buffer.from(arrayBuffer, 0, readLen);
  7426. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7427. // 检查 buf 是否为空
  7428. if (buf.length === 0) {
  7429. throw new Error("Buffer is empty after reading the file");
  7430. }
  7431. try {
  7432. // 检测文件编码
  7433. // let detectedEncoding = chardet.detect(buf);
  7434. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  7435. let detectedEncoding = this.detect(arrayBuffer)
  7436. console.info("onecoldT Detected encoding: " + detectedEncoding);
  7437. // 使用检测到的编码解码,解决中文乱码问题
  7438. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7439. console.info("onecoldT Detected textDecoder: " + textDecoder);
  7440. let fileContent = textDecoder.decode(buf);
  7441. console.info(`onecoldT The content of file1: ${fileContent}`);
  7442. //解密
  7443. if (isJiaMi) {
  7444. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  7445. }
  7446. console.info(`onecold The content of file2: ${fileContent}`);
  7447. this.lyricContent = fileContent
  7448. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  7449. this.lyricConStr = fileContent
  7450. }
  7451. // 将文件内容按行分割成字符串数组
  7452. let lines = fileContent.split('\n').map(line => line.trim());
  7453. console.info(`onecold The content of file: ${fileContent}`);
  7454. // 3.解析歌词
  7455. let lyric = this.parser.parse(lines);
  7456. // 4.设置歌词
  7457. this.lyricController.setLyric(lyric);
  7458. this.lyricControllerXF.setLyric(lyric)
  7459. this.lyricControllerSingle.setLyric(lyric)
  7460. this.showSingleLyric = true
  7461. console.info(`The content of file: ${fileContent}`);
  7462. } catch (chardetError) {
  7463. console.error("chardet.detect failed with error: " + chardetError.message);
  7464. this.lyricController.setLyric(null);
  7465. this.lyricControllerXF.setLyric(null)
  7466. this.lyricControllerSingle.setLyric(null)
  7467. }
  7468. })
  7469. .catch((err: BusinessError) => {
  7470. this.lyricController.setLyric(null)
  7471. this.lyricControllerXF.setLyric(null)
  7472. this.lyricControllerSingle.setLyric(null)
  7473. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  7474. })
  7475. .catch((err: Error) => {
  7476. this.lyricController.setLyric(null)
  7477. this.lyricControllerXF.setLyric(null)
  7478. this.lyricControllerSingle.setLyric(null)
  7479. console.error("read file 2 data failed with error message: " + err.message);
  7480. })
  7481. .finally(() => {
  7482. fs.closeSync(file);
  7483. });
  7484. } catch (error) {
  7485. this.lyricController.setLyric(null)
  7486. this.lyricControllerSingle.setLyric(null)
  7487. this.lyricControllerXF.setLyric(null)
  7488. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  7489. }
  7490. }
  7491. detect(data: ArrayBuffer): string {
  7492. //创建检测对象
  7493. let detector: UniversalDetector = new UniversalDetector();
  7494. // 传入检测数据并实时判断编码格式
  7495. detector.handleData(data, 0, data.byteLength);
  7496. // 标记检测数据 读取结束
  7497. detector.dataEnd();
  7498. // 获取检测结果
  7499. let detected: string = detector.getDetectedCharset();
  7500. // 释放资源
  7501. detector.reset();
  7502. return detected;
  7503. }
  7504. //初始化悬浮歌词的自定义设置
  7505. initPipLyricSetting() {
  7506. this.lyricControllerXF
  7507. .setTextSize(this.currentLyricSize)
  7508. .setCacheSize(4)
  7509. .setTextColor("#DDDDDD")
  7510. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  7511. .setEmptyHint("")
  7512. .setAnimationDuration(1000)
  7513. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  7514. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  7515. this.setBlurDegree(this.blurDegreePip, true)
  7516. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  7517. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  7518. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  7519. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  7520. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  7521. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  7522. this.lyricControllerXF.setHightLightCenter(true)
  7523. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  7524. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7525. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7526. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  7527. if (this.pipBgIndex === 0) {
  7528. if (this.cover) {
  7529. this.pipBg = this.cover
  7530. } else {
  7531. this.pipBg = this.imageColor
  7532. }
  7533. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7534. }
  7535. }
  7536. //根据item返回歌词内容
  7537. async getLyricContent(item: VideoItem): Promise<string> {
  7538. let neiqianLrc = ''
  7539. let lyContent = item?.lyricContent
  7540. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  7541. neiqianLrc = lyContent
  7542. return neiqianLrc
  7543. }
  7544. try {
  7545. //取数据库里面的歌词lyContent
  7546. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  7547. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  7548. console.log("onecold Lyrics:", lyricContent);
  7549. neiqianLrc = lyricContent
  7550. return neiqianLrc
  7551. }
  7552. } catch (error) {
  7553. console.error("Error fetching lyrics:", error);
  7554. }
  7555. try {
  7556. let filePath = item.filePath;
  7557. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  7558. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  7559. let isJiaMi = false;
  7560. let realLyricPath = lyricPath;
  7561. if (FileUtil.accessSync(jiaMilyricPath)) {
  7562. isJiaMi = true;
  7563. realLyricPath = jiaMilyricPath;
  7564. console.info("onecold 找到加密本地歌词");
  7565. } else {
  7566. console.info("onecold 找到本地歌词");
  7567. }
  7568. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7569. const stat = await fileIo.stat(file.fd);
  7570. const arrayBuffer = new ArrayBuffer(stat.size);
  7571. const readLen = await fs.read(file.fd, arrayBuffer);
  7572. console.info("read file data succeed");
  7573. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7574. if (buf.length === 0) {
  7575. throw new Error("Buffer is empty after reading the file");
  7576. }
  7577. // let detectedEncoding = chardet.detect(buf);
  7578. let detectedEncoding = this.detect(arrayBuffer)
  7579. console.info("Detected encoding: " + detectedEncoding);
  7580. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7581. let fileContent = textDecoder.decode(buf);
  7582. console.info(`onecold The content of file1: ${fileContent}`);
  7583. if (isJiaMi) {
  7584. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  7585. }
  7586. console.info(`onecold The content of file2: ${fileContent}`);
  7587. fs.closeSync(file);
  7588. return fileContent;
  7589. } catch (error) {
  7590. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  7591. return '';
  7592. }
  7593. }
  7594. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  7595. if (StrUtil.isEmpty(filePath)) {
  7596. return
  7597. }
  7598. try {
  7599. //将content进行加密
  7600. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  7601. let lyricContent = ''
  7602. if (isJiaMi) {
  7603. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  7604. } else {
  7605. lyricContent = content
  7606. }
  7607. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  7608. // 清空文件内容
  7609. await fileIo.truncate(file.fd, 0);
  7610. await fileIo.write(file.fd, lyricContent);
  7611. await fileIo.close(file);
  7612. console.log('onecold lyric file Data saved successfully.');
  7613. } catch (error) {
  7614. console.error('onecold lyric file Failed to save data:', error);
  7615. }
  7616. }
  7617. /**
  7618. * Get largest proportion color of an image.
  7619. */
  7620. getImageColor() {
  7621. if (!this.context) {
  7622. return;
  7623. }
  7624. let bg = Utility.getMusisBg()
  7625. this.imageLabel = bg
  7626. ColorConversion.setSysBarLightBackground(true);
  7627. this.context.resourceManager.getMediaContent(bg)
  7628. .then((value: Uint8Array) => {
  7629. let buffer = value.buffer as ArrayBuffer;
  7630. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  7631. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  7632. if (error) {
  7633. Logger.error('Failed to create color picker.');
  7634. } else {
  7635. let color = colorPicker.getLargestProportionColor();
  7636. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  7637. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  7638. }
  7639. })
  7640. let headFilter = effectKit.createEffect(pixelMap);
  7641. if (headFilter !== null) {
  7642. headFilter.blur(15);
  7643. headFilter.getEffectPixelMap().then((value) => {
  7644. this.imageLabelBg = value;
  7645. })
  7646. }
  7647. })
  7648. .catch((error: BusinessError) => {
  7649. Logger.error(`${error.code} + ${error.message}`)
  7650. })
  7651. })
  7652. .catch((error: BusinessError) => {
  7653. Logger.error(`${error.code} + ${error.message}`)
  7654. })
  7655. }
  7656. setImageColor(cover: string) {
  7657. if (!this.context) {
  7658. return;
  7659. }
  7660. if (cover === undefined) {
  7661. return;
  7662. }
  7663. imagePathToPixelMap(cover).then((value) => {
  7664. let headFilter = effectKit.createEffect(value);
  7665. if (headFilter !== null) {
  7666. headFilter.blur(15);
  7667. headFilter.getEffectPixelMap().then((value) => {
  7668. this.imageLabelBg = value;
  7669. })
  7670. }
  7671. }).catch((error: BusinessError) => {
  7672. Logger.error(`${error.code} + ${error.message}`)
  7673. })
  7674. }
  7675. setImageColor2(cover: string) {
  7676. if (!this.context) {
  7677. return;
  7678. }
  7679. if (cover === undefined) {
  7680. return;
  7681. }
  7682. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  7683. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  7684. this.imageColor = data.imageColor;
  7685. if (data.blurPixelMap) {
  7686. this.imageLabelBg = data.blurPixelMap;
  7687. }
  7688. })
  7689. }
  7690. // 定义开始旋转的方法
  7691. // 定时器用于一百毫秒执行一次旋转角度
  7692. @State timer: number = 0
  7693. @State rotateAngle: number = 0
  7694. //封面旋转动画
  7695. animationRoFun() {
  7696. if (this.isPlaying && !this.isCoverRectangle) {
  7697. this.timer = setInterval(() => {
  7698. this.rotateAngle += 1
  7699. }, 100)
  7700. this.startRotation()
  7701. } else {
  7702. clearInterval(this.timer)
  7703. this.stopRotation()
  7704. }
  7705. }
  7706. // 定义开始旋转的方法
  7707. startRotation() {
  7708. if (this.isPlaying) {
  7709. animateTo({
  7710. duration: 777,
  7711. iterations: 1,
  7712. curve: Curve.Linear
  7713. }, () => {
  7714. this.rotateAngle2 = -9
  7715. })
  7716. }
  7717. }
  7718. // 回调,暂停和播放按钮回调,下一首和上一首
  7719. playChange() {
  7720. // if(this.isCoverRectangle){
  7721. // return
  7722. // }
  7723. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7724. this.setIsPlaying(true)
  7725. this.animationState = AnimationStatus.Running
  7726. } else {
  7727. this.setIsPlaying(false)
  7728. this.animationState = AnimationStatus.Paused
  7729. }
  7730. }
  7731. // 定义停止旋转的方法
  7732. stopRotation() {
  7733. if (this.isCoverRectangle) {
  7734. this.rotateAngle = 0
  7735. } else {
  7736. //唱针以左上角为点选择逆时针40度
  7737. animateTo({
  7738. duration: 1000,
  7739. curve: Curve.Linear,
  7740. iterations: 1,
  7741. }, () => {
  7742. this.rotateAngle2 = -45;
  7743. });
  7744. }
  7745. }
  7746. @Builder
  7747. private LyricsTopItem() {
  7748. Row() {
  7749. Stack() {
  7750. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7751. .height(62)
  7752. .width(62)
  7753. .alt(this.imageLabel)
  7754. .borderRadius(8)
  7755. .clickEffect({ level: ClickEffectLevel.HEAVY })
  7756. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  7757. .shadow({
  7758. radius: 22,
  7759. type: ShadowType.BLUR,
  7760. color: 'on_primary'
  7761. })
  7762. }
  7763. .width('18%')
  7764. Column() {
  7765. Column() {
  7766. Text(this.name)
  7767. .fontSize(16)
  7768. .maxLines(1)
  7769. .fontWeight(FontWeight.Bolder)
  7770. .fontColor(this.currentLyricColor)
  7771. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7772. Row() {
  7773. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  7774. .fontSize(13)
  7775. .fontWeight(FontWeight.Bold)
  7776. .padding({ top: 8 })
  7777. .fontColor(this.currentLyricColor)
  7778. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7779. Blank()
  7780. }
  7781. }
  7782. .height('100%')
  7783. .width('100%')
  7784. .justifyContent(FlexAlign.Center)
  7785. .alignItems(HorizontalAlign.Start)
  7786. }
  7787. .height('100%')
  7788. .width('65%')
  7789. Column() {
  7790. Image($r('app.media.lyric'))
  7791. .width(28)
  7792. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7793. .margin({ right: 30 })
  7794. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7795. .onClick(() => {
  7796. this.isLyricSetting = !this.isLyricSetting;
  7797. })
  7798. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  7799. height: '95%',
  7800. dragBar: true,
  7801. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7802. showClose: true,
  7803. blurStyle: BlurStyle.Thin,
  7804. backgroundColor: Color.Transparent,
  7805. // title: { title: $r('app.string.lyric_setting') }
  7806. })
  7807. }
  7808. .width('18%')
  7809. }
  7810. .width('82%')
  7811. .height(58)
  7812. .justifyContent(FlexAlign.SpaceBetween)
  7813. }
  7814. //歌词显示
  7815. @Builder
  7816. PlayerLyrics() {
  7817. Column() {
  7818. Column() {
  7819. this.LyricsTopItem()
  7820. }
  7821. .height(this.isPuraWP() ? 15 : 58)
  7822. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  7823. Visibility.None : Visibility.Visible)
  7824. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  7825. .width("100%")
  7826. Column() {
  7827. LyricView2({
  7828. controller: this.lyricController,
  7829. enableSeek: true,
  7830. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7831. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7832. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7833. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  7834. if (!this.isPlaying) {
  7835. console.info('onecold startPlayOrResumePlay 7527')
  7836. this.startPlayOrResumePlay()
  7837. }
  7838. else {
  7839. this.isSeekTo = true;
  7840. this.mDestroyPage = false;
  7841. this.showLoadIng();
  7842. this.seekTo(position + "");
  7843. this.isSeekTo = false;
  7844. }
  7845. return true
  7846. }
  7847. })
  7848. .width("100%")
  7849. .layoutWeight(1)
  7850. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  7851. if (this.isPhoneLan()) {
  7852. Column() {
  7853. this.playProgressView()
  7854. // this.playCenterView()
  7855. }
  7856. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  7857. }
  7858. }
  7859. .position({
  7860. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  7861. (this.isPuraWP() ? 58 : 99)
  7862. })
  7863. .justifyContent(FlexAlign.Center)
  7864. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  7865. }
  7866. }
  7867. @Builder
  7868. SingleLyricView() {
  7869. Column() {
  7870. Column() {
  7871. LyricView2({
  7872. controller: this.lyricControllerSingle,
  7873. enableSeek: false,
  7874. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7875. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7876. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7877. })
  7878. }
  7879. .height(66)
  7880. .margin({ bottom: 20 })
  7881. }
  7882. }
  7883. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  7884. @Builder
  7885. BottomControl() {
  7886. Column() {
  7887. this.TopPlayProgressView()
  7888. //播放 暂停,下一首,上一首
  7889. this.playCenterView()
  7890. //播放进度条
  7891. this.BottomView()
  7892. }
  7893. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  7894. }
  7895. //播放控制上一首 下一首 暂停和播放
  7896. @Builder
  7897. playCenterView(){
  7898. Row() {
  7899. Row({ space: 20 }) {
  7900. Button({type:ButtonType.Circle,stateEffect:true}){
  7901. //更多功能
  7902. Image($r('app.media.menu'))
  7903. .width(24)
  7904. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7905. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  7906. height: this.isCoverOpacity() ? '95%' : '93%',
  7907. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  7908. dragBar: true,
  7909. showClose: true,
  7910. blurStyle: BlurStyle.Thin,
  7911. backgroundColor: Color.Transparent,
  7912. })
  7913. }
  7914. .margin({ left: 5 })
  7915. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7916. .backgroundColor(Color.Transparent)
  7917. .onClick(() => {
  7918. this.isShowMoreView = !this.isShowMoreView;
  7919. })
  7920. Button({type:ButtonType.Circle,stateEffect:true}){
  7921. Image($r('app.media.ic_previous'))
  7922. .width(33)
  7923. .clickEffect({level:ClickEffectLevel.HEAVY})
  7924. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7925. }
  7926. .onClick(async () => {
  7927. this.playPrevious()
  7928. })
  7929. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7930. .backgroundColor(Color.Transparent)
  7931. .margin({ left: 5 })
  7932. }
  7933. Button({type:ButtonType.Circle,stateEffect:true}){
  7934. Column() {
  7935. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  7936. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  7937. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  7938. .width(this.isPhoneLan()?45:55)
  7939. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7940. .fillColor(Color.White)
  7941. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7942. .onClick(async () => {
  7943. console.info('onecold playOrPause 7651')
  7944. this.playOrPause()
  7945. })
  7946. }
  7947. }
  7948. .backgroundColor(Color.Transparent)
  7949. .layoutWeight(1)
  7950. // .margin({ left: 38, right: 38 })
  7951. Row({ space: 20 }) {
  7952. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7953. Image($r('app.media.ic_next'))
  7954. .width(33)
  7955. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7956. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7957. .onClick(() => {
  7958. this.playNext();
  7959. })
  7960. }
  7961. .backgroundColor(Color.Transparent)
  7962. .margin({ right: 5 })
  7963. .width(33)
  7964. if(this.isPhoneLan()){
  7965. this.fullButton()
  7966. }else{
  7967. Button({type:ButtonType.Circle,stateEffect:true}){
  7968. //添加或取消收藏
  7969. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  7970. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  7971. .fontSize(23)
  7972. .fontColor([Color.White])
  7973. .alignSelf(ItemAlign.Center)
  7974. // .width(24)
  7975. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7976. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7977. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7978. .onClick(async () => {
  7979. if(this.currentSong){
  7980. this.doFav(this.currentSong)
  7981. }
  7982. })
  7983. }
  7984. .backgroundColor(Color.Transparent)
  7985. .width(24)
  7986. }
  7987. }
  7988. // .margin({ left: 5 })
  7989. }
  7990. .width('95%')
  7991. .margin({ bottom:this.isCoverOpacity()?0:20 })
  7992. .justifyContent(FlexAlign.SpaceEvenly)
  7993. }
  7994. @Builder
  7995. TopPlayProgressView(){
  7996. Row() {
  7997. Column(){
  7998. Row(){
  7999. Stack(){
  8000. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  8001. .fontColor([Color.White])
  8002. .fontSize(21)
  8003. .effectStrategy(1)
  8004. Text(this.fastForwardSeconds)
  8005. .fontColor(Color.White)
  8006. .fontSize(10)
  8007. .fontWeight(FontWeight.Bold)
  8008. }
  8009. .margin({left:12,bottom:6})
  8010. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8011. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8012. .onClick(()=>{
  8013. this.backForward()
  8014. })
  8015. Slider({
  8016. value: this.progressValue,
  8017. min: 0,
  8018. max: this.PROGRESS_MAX_VALUE,
  8019. step: 1,
  8020. style: SliderStyle.InSet
  8021. })
  8022. .height(20)
  8023. .blockColor('rgba(255,255,255,1)')
  8024. .trackColor('rgba(255,255,255,0.3)')
  8025. .selectedColor(Color.White)
  8026. .trackThickness(4)
  8027. .layoutWeight(1)
  8028. .showSteps(false)
  8029. .showTips(true)
  8030. .alignSelf(ItemAlign.Center)
  8031. .enabled(this.slideEnable)
  8032. .onChange((value: number, mode: SliderChangeMode) => {
  8033. // if (mode == 2) {
  8034. this.isSeekTo = true;
  8035. this.mDestroyPage = false;
  8036. this.showLoadIng();
  8037. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8038. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8039. this.seekTo(seekValue + "");
  8040. // this.setProgress()
  8041. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8042. this.isSeekTo = false;
  8043. // }
  8044. })
  8045. Stack(){
  8046. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  8047. .fontColor([Color.White])
  8048. .fontSize(21)
  8049. .effectStrategy(1)
  8050. Text(this.fastForwardSeconds)
  8051. .fontColor(Color.White)
  8052. .fontSize(10)
  8053. .fontWeight(FontWeight.Bold)
  8054. }
  8055. .margin({right:10,bottom:6})
  8056. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8057. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8058. .onClick(()=>{
  8059. this.fastForward()
  8060. })
  8061. }
  8062. .padding({ right: 7,left:22 })
  8063. Row(){
  8064. Text(this.currentTime)
  8065. .fontSize(10)
  8066. .fontColor(Color.White)
  8067. Blank()
  8068. .layoutWeight(1)
  8069. Text(this.totalTime)
  8070. .fontSize(10)
  8071. .fontColor(Color.White)
  8072. }
  8073. .justifyContent(FlexAlign.Start)
  8074. .padding({ right: 18,left:36 })
  8075. }
  8076. }
  8077. //x5的竖屏模式需要99%
  8078. .width(this.isLandscape?'80%':'93%')
  8079. .justifyContent(FlexAlign.Center)
  8080. .margin({bottom:6})
  8081. .animation({
  8082. duration: 666,
  8083. curve: 'ease-in-out' // 可选动画曲线
  8084. })
  8085. }
  8086. //播放进度条
  8087. @Builder
  8088. BottomView(){
  8089. Row() {
  8090. Button({type:ButtonType.Circle,stateEffect:true}){
  8091. Column() {
  8092. if (this.playType === 0) {
  8093. Image($r('app.media.loop'))
  8094. .width(27)
  8095. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8096. } else if (this.playType === 1) {
  8097. Image($r('app.media.single'))
  8098. .width(27)
  8099. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8100. } else if (this.playType === 2) {
  8101. Image($r('app.media.normal_play'))
  8102. .width(27)
  8103. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8104. } else if (this.playType === 3) {
  8105. Image($r('app.media.random'))
  8106. .width(27)
  8107. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8108. }
  8109. }
  8110. }
  8111. .layoutWeight(1)
  8112. .margin({ left: 5 })
  8113. .backgroundColor(Color.Transparent)
  8114. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8115. .onClick(async () => {
  8116. this.setLoopMode()
  8117. })
  8118. this.fullButton()
  8119. Button({type:ButtonType.Circle,stateEffect:true}){
  8120. Column() {
  8121. Image($r('app.media.lyric'))
  8122. .width(26)
  8123. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8124. }
  8125. }
  8126. .layoutWeight(1)
  8127. .backgroundColor(Color.Transparent)
  8128. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8129. .onClick(async () => {
  8130. this.isLyricSetting = !this.isLyricSetting;
  8131. })
  8132. //播放列表
  8133. Button({type:ButtonType.Circle,stateEffect:true}){
  8134. Image($r('app.media.hm_playlist'))
  8135. .width(24)
  8136. .fillColor(Color.White)
  8137. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8138. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8139. height: '95%',
  8140. dragBar: true,
  8141. showClose: true,
  8142. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8143. blurStyle: BlurStyle.Thin,
  8144. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  8145. title: {
  8146. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8147. + `(${this.songList.length}首)`
  8148. }
  8149. })
  8150. }
  8151. .layoutWeight(1)
  8152. .backgroundColor(Color.Transparent)
  8153. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8154. .onClick(() => {
  8155. this.isShowSheetView = !this.isShowSheetView;
  8156. if(this.isPlayListBgGrass){
  8157. this.isFrontWhite = true
  8158. }else{
  8159. this.isFrontWhite = false
  8160. }
  8161. this.scrollIndex()
  8162. })
  8163. }
  8164. .width(this.isLandscape?'88%':'95%')
  8165. .justifyContent(FlexAlign.SpaceAround)
  8166. .height(30)
  8167. .margin({top:3})
  8168. .animation({
  8169. duration: 666,
  8170. curve: 'ease-in-out' // 可选动画曲线
  8171. })
  8172. }
  8173. @Builder
  8174. fullButton(){
  8175. Button({type:ButtonType.Circle,stateEffect:true}){
  8176. Column() {
  8177. Image($r('app.media.full_4'))
  8178. .width(25)
  8179. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8180. }
  8181. }
  8182. .layoutWeight(1)
  8183. .backgroundColor(Color.Transparent)
  8184. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8185. .onClick(async () => {
  8186. if (this.isLandscape) {
  8187. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8188. } else {
  8189. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8190. }
  8191. })
  8192. }
  8193. //旧版本播放进度条
  8194. @Builder
  8195. playProgressView() {
  8196. Row() {
  8197. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8198. Column() {
  8199. if (this.playType === 0) {
  8200. Image($r('app.media.loop'))
  8201. .width($r('app.float.control_image_width'))
  8202. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8203. } else if (this.playType === 1) {
  8204. Image($r('app.media.single'))
  8205. .width($r('app.float.control_image_width'))
  8206. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8207. } else if (this.playType === 2) {
  8208. Image($r('app.media.normal_play'))
  8209. .width($r('app.float.control_image_width'))
  8210. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8211. } else if (this.playType === 3) {
  8212. Image($r('app.media.random'))
  8213. .width($r('app.float.control_image_width'))
  8214. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8215. }
  8216. }
  8217. }
  8218. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8219. .animation({
  8220. duration: 666,
  8221. curve: 'ease-in-out' // 可选动画曲线
  8222. })
  8223. .backgroundColor(Color.Transparent)
  8224. .margin({ right: 10 })
  8225. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8226. .onClick(async () => {
  8227. this.setLoopMode()
  8228. })
  8229. Text(this.currentTime)
  8230. .fontSize($r('app.float.slider_font_size'))
  8231. .fontColor(Color.White)
  8232. .margin(3)
  8233. Slider({
  8234. value: this.progressValue,
  8235. min: 0,
  8236. max: this.PROGRESS_MAX_VALUE,
  8237. step: 1,
  8238. style: SliderStyle.OutSet
  8239. })
  8240. .width('600px')
  8241. .blockColor('rgba(255,255,255,1)')
  8242. .trackColor('rgba(255,255,255,0.3)')
  8243. .selectedColor(Color.White)
  8244. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  8245. .layoutWeight(1)
  8246. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8247. .showSteps(false)
  8248. .showTips(true)
  8249. .enabled(this.slideEnable)
  8250. .onChange((value: number, mode: SliderChangeMode) => {
  8251. // if (mode == 2) {
  8252. this.isSeekTo = true;
  8253. this.mDestroyPage = false;
  8254. this.showLoadIng();
  8255. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8256. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8257. this.seekTo(seekValue + "");
  8258. // this.setProgress()
  8259. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8260. this.isSeekTo = false;
  8261. // }
  8262. })
  8263. Text(this.totalTime)
  8264. .fontSize($r('app.float.slider_font_size'))
  8265. .fontColor(Color.White)
  8266. .margin(3)
  8267. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8268. //播放列表
  8269. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8270. Image($r('app.media.hm_playlist'))
  8271. .width($r('app.float.control_image_width'))
  8272. .fillColor(Color.White)
  8273. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8274. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8275. height: '95%',
  8276. dragBar: true,
  8277. showClose: true,
  8278. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8279. blurStyle: BlurStyle.Thin,
  8280. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  8281. title: {
  8282. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8283. + `(${this.songList.length}首)`
  8284. }
  8285. })
  8286. }
  8287. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8288. .animation({
  8289. duration: 666,
  8290. curve: 'ease-in-out' // 可选动画曲线
  8291. })
  8292. .backgroundColor(Color.Transparent)
  8293. .margin({ right: 20, left: 10 })
  8294. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8295. .onClick(() => {
  8296. this.isShowSheetView = !this.isShowSheetView;
  8297. if (this.isPlayListBgGrass) {
  8298. this.isFrontWhite = true
  8299. } else {
  8300. this.isFrontWhite = false
  8301. }
  8302. this.scrollIndex()
  8303. })
  8304. }
  8305. //x5的竖屏模式需要99%
  8306. .width(this.isPhonePortrait() ? '93.4%'
  8307. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  8308. .height(this.isPhoneLan() ? 25 : 33)
  8309. .animation({
  8310. duration: 666,
  8311. curve: 'ease-in-out' // 可选动画曲线
  8312. })
  8313. }
  8314. isBigScreen() {
  8315. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  8316. return true
  8317. }
  8318. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8319. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8320. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  8321. return false
  8322. } else {
  8323. return true
  8324. }
  8325. return false
  8326. }
  8327. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  8328. @State isCoverRectangle: boolean = false
  8329. @State isCoverTop: boolean = true
  8330. // 添加控制缩放的状态变量
  8331. @State scaleValueImage: number = 1
  8332. @Builder
  8333. CoverInfo() {
  8334. Column() {
  8335. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  8336. if (this.isCoverRectangle) {
  8337. if (!this.isCoverTop) {
  8338. this.musicNameInfo(false)
  8339. }
  8340. } else {
  8341. this.musicNameInfo(false)
  8342. }
  8343. Stack() {
  8344. // 唱片旋转效果
  8345. Image($r('app.media.ic_music_disc'))
  8346. .width(245)
  8347. .height(245)
  8348. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  8349. .aspectRatio(1)
  8350. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8351. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8352. .borderRadius('100%')
  8353. .align(Alignment.Center)
  8354. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  8355. .rotate({
  8356. angle: this.rotateAngle,
  8357. centerX: "50%",
  8358. centerY: "50%",
  8359. })
  8360. .animation({
  8361. duration: 100,
  8362. curve: Curve.Linear
  8363. })
  8364. .shadow({
  8365. radius: 22,
  8366. type: ShadowType.BLUR,
  8367. color: 'on_primary'
  8368. })
  8369. Column() {
  8370. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  8371. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8372. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  8373. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  8374. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8375. .alt(this.imageLabel)
  8376. .margin({ right: 8, left: 8, top: 8 })
  8377. .aspectRatio(1)
  8378. .opacity(this.opacityValueImage)
  8379. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8380. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8381. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8382. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8383. .align(Alignment.Center)//
  8384. .clip(true)
  8385. .rotate({
  8386. x: 0,
  8387. y: 0,
  8388. z: 1,
  8389. angle: this.rotateAngle
  8390. })
  8391. .shadow({
  8392. radius: 22,
  8393. type: ShadowType.BLUR,
  8394. color: 'on_primary'
  8395. })
  8396. .onClick(() => {
  8397. this.getImageColor()
  8398. })
  8399. this.musicNameInfo(false)
  8400. } else {
  8401. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8402. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  8403. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  8404. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8405. .alt(this.imageLabel)
  8406. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  8407. .aspectRatio(1)
  8408. .opacity(this.opacityValueImage)
  8409. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8410. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8411. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8412. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8413. .align(Alignment.Center)//
  8414. .clip(true)
  8415. .shadow({
  8416. radius: 22,
  8417. type: ShadowType.BLUR,
  8418. color: 'on_primary'
  8419. })
  8420. .rotate({
  8421. x: 0,
  8422. y: 0,
  8423. z: 1,
  8424. angle: this.rotateAngle
  8425. })
  8426. .onClick(() => {
  8427. this.getImageColor()
  8428. })
  8429. if (this.isPhoneLan()) {
  8430. Text(this.name)
  8431. .fontSize(18)
  8432. .fontWeight(FontWeight.Bold)
  8433. .margin({ top: 13 })
  8434. .textOverflow({ overflow: TextOverflow.Ellipsis })
  8435. .maxLines(1)
  8436. .width('99%')
  8437. .textAlign(TextAlign.Center)
  8438. .fontColor(Color.White)
  8439. }
  8440. }
  8441. }
  8442. // 唱针以左上角为点选择逆时针40度
  8443. Image($r('app.media.ic_music_cover_hand'))
  8444. .height(130)
  8445. .margin({ bottom: 220, top: 0 })
  8446. .align(Alignment.Top)
  8447. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  8448. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8449. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8450. Column({ space: 8 }) {
  8451. Text(this.name)
  8452. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  8453. .fontWeight(FontWeight.Bold)
  8454. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8455. .maxLines(1)
  8456. .width('48%')
  8457. .textAlign(TextAlign.Center)
  8458. .fontColor(Color.White)
  8459. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8460. Text(this.artist)
  8461. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  8462. .fontColor(Color.White)
  8463. .fontWeight(FontWeight.Bold)
  8464. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8465. }
  8466. .justifyContent(FlexAlign.Start)
  8467. .zIndex(1)
  8468. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  8469. }
  8470. .margin({
  8471. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  8472. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  8473. top: this.isCoverOpacity() ? 0 : 20
  8474. })
  8475. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  8476. this.SingleLyricView()
  8477. }
  8478. if (this.isPhoneLan()) {
  8479. Column() {
  8480. this.playCenterView()
  8481. // this.playProgressView()
  8482. }
  8483. .position({ left: 28, bottom: 38 })
  8484. } else {
  8485. this.BottomControl()
  8486. }
  8487. }
  8488. .width(CommonConstants.FULL_PERCENT)
  8489. .clip(true)
  8490. }
  8491. @Builder
  8492. private musicNameInfo(isHidden: boolean) {
  8493. Column({ space: 8 }) {
  8494. Text(this.name)
  8495. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  8496. .fontWeight(FontWeight.Bold)
  8497. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8498. .maxLines(1)
  8499. .width('99%')
  8500. .textAlign(TextAlign.Center)
  8501. .fontColor(Color.White)
  8502. Text(this.artist + ' ' + this.currentSong?.album)
  8503. .fontSize(this.isCoverOpacity() ? 12 : 15)
  8504. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8505. .fontColor(Color.White)
  8506. .textAlign(TextAlign.Center)
  8507. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  8508. .width('99%')
  8509. .maxLines(1)
  8510. }
  8511. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  8512. .zIndex(1)
  8513. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8514. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  8515. }
  8516. @Builder
  8517. private PlayTitle() {
  8518. Row() {
  8519. Row() {
  8520. Image($r('app.media.ic_back_down'))
  8521. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  8522. .hitTestBehavior(HitTestMode.Transparent)
  8523. Text(this.name + ' ' + this.artist)
  8524. .fontColor(Color.White)
  8525. .fontSize($r('app.float.title_font_size'))
  8526. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8527. .maxLines(1)
  8528. .visibility(Visibility.None)
  8529. .margin({ left: 2, right: 30 })
  8530. }
  8531. .layoutWeight(1)
  8532. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8533. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  8534. .onClick(() => {
  8535. this.isShowPlay = false;
  8536. })
  8537. Column() {
  8538. AVCastPicker({
  8539. normalColor: Color.White,
  8540. onStateChange: this.onStateVastChange
  8541. })
  8542. .width(24)
  8543. .height(24)
  8544. }
  8545. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  8546. }
  8547. .width(PlayConstants.ROW_WIDTH)
  8548. }
  8549. @Builder
  8550. lyricSettingSheet(isPip: boolean) {
  8551. Scroll() {
  8552. this.lyricSetting(isPip)
  8553. }
  8554. .width('100%')
  8555. .height('100%')
  8556. }
  8557. @Builder
  8558. lyricSetting(isPip: boolean) {
  8559. Column() {
  8560. // 时间调节模块
  8561. if (!isPip) {
  8562. this.BuildTimeControls()
  8563. }
  8564. // 字号控制模块
  8565. this.BuildFontControls(isPip)
  8566. }
  8567. }
  8568. // 歌词时间偏移状态
  8569. @State timeOffset: number = 0.0
  8570. @State currentLyricColor: string = '#FFFFFF'
  8571. @State currentLyricColorPip: string = '#FFFFFF'
  8572. @State currentHighLightLyricColor: string = '#FF4081'
  8573. @State currentHighLightLyricColorPip: string = '#FF4081'
  8574. // 歌词字号状态
  8575. @State currentLyricSize: number = 20
  8576. @State currentLyricSizePip: number = 20
  8577. // 高亮歌词放大倍数
  8578. @State currentHightLyricSize: number = 1.2
  8579. @State currentHightLyricSizePip: number = 1.2
  8580. @State currentLyricLineSpace: number = 10
  8581. @State currentLyricLineSpacePip: number = 10
  8582. @State currentLyricAlignMode: number = 1
  8583. @State currentLyricAlignModePip: number = 1
  8584. @State blurDegree: number = 2
  8585. @State blurDegreePip: number = 2
  8586. @State isShowSelectColor: boolean = false
  8587. @State isShowHLSelectColor: boolean = false
  8588. @State isShowPipBgSelectColor: boolean = false
  8589. @State pipLyWidth: number = 330
  8590. @State pipLyHeight: number = 120
  8591. // 构建颜色选择器
  8592. @Builder
  8593. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  8594. Row({ space: 10 }) {
  8595. HSBColorPicker({
  8596. color: '#FFFFFF',
  8597. radius: 8,
  8598. layout: HSBColorPickerLayout.COLUMN,
  8599. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  8600. '#fa7105'],
  8601. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  8602. this.changeLyricColor(value, isPip, isBGPip)
  8603. })
  8604. .height(250)
  8605. .layoutWeight(1)
  8606. .padding(25)
  8607. }
  8608. .width('66%')
  8609. }
  8610. @State isOpenPip: boolean = false
  8611. @State pipBgIndex: number = 0
  8612. // 构建字号控制器
  8613. @Builder
  8614. BuildFontControls(isPip: boolean) {
  8615. Column() {
  8616. if (isPip) {
  8617. Column() {
  8618. Row() {
  8619. Text('悬浮歌词')
  8620. .margin({ left: 18 })
  8621. .fontSize(15)
  8622. .fontColor(Color.White)
  8623. .fontWeight(480)
  8624. .layoutWeight(1)
  8625. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  8626. .selectedColor(this.themeColor)
  8627. .switchPointColor(Color.White)
  8628. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8629. .margin({ right: 18 })
  8630. .onChange((checked: boolean) => {
  8631. this.isOpenPip = checked;
  8632. if (this.isOpenPip) {
  8633. this.startPip()
  8634. } else {
  8635. this.stopPip()
  8636. }
  8637. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  8638. })
  8639. .width(50)
  8640. .height(30);
  8641. }
  8642. .height(55)
  8643. }
  8644. .backgroundColor(Color.Transparent)
  8645. .borderRadius(15)
  8646. .margin({
  8647. left: 30,
  8648. right: 30,
  8649. top: 0,
  8650. bottom: 20
  8651. })
  8652. .padding(0)
  8653. .border({
  8654. color: Color.White,
  8655. width: 1.8
  8656. })
  8657. }else{
  8658. Column() {
  8659. Row() {
  8660. Text('单行歌词')
  8661. .margin({ left: 18 })
  8662. .fontSize(15)
  8663. .fontColor(Color.White)
  8664. .fontWeight(480)
  8665. .layoutWeight(1)
  8666. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  8667. .selectedColor(this.themeColor)
  8668. .switchPointColor(Color.White)
  8669. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8670. .margin({ right: 18 })
  8671. .onChange((checked: boolean) => {
  8672. this.isShowSingleLineLyric = checked;
  8673. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  8674. })
  8675. .width(50)
  8676. .height(30);
  8677. }
  8678. .height(55)
  8679. }
  8680. .backgroundColor(Color.Transparent)
  8681. .borderRadius(15)
  8682. .margin({
  8683. left: 30,
  8684. right: 30,
  8685. top: 10,
  8686. bottom: 10
  8687. })
  8688. .padding(0)
  8689. .border({
  8690. color: Color.White,
  8691. width: 1.8
  8692. })
  8693. }
  8694. Row() {
  8695. Text(`歌词居中:`)
  8696. .fontSize(14)
  8697. .fontColor(Color.White)
  8698. .margin({ left: 2 })
  8699. Row() {
  8700. ForEach(['居中', '居左'], (size: string, index: number) => {
  8701. Button(size)
  8702. .width(60)
  8703. .height(28)
  8704. .fontSize(12)
  8705. .fontColor('#FFFFFF')
  8706. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  8707. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  8708. .border({
  8709. color: (!isPip && this.currentLyricAlignMode === index) ||
  8710. (isPip && this.currentLyricAlignModePip === index) ?
  8711. '#007DFF' : '#DDDDDD',
  8712. width: 1.8
  8713. })
  8714. .onClick(() => {
  8715. this.setLyricAlignMode(index, isPip)
  8716. })
  8717. .margin({ left: 10, right: 8 })
  8718. })
  8719. }
  8720. .width('76%')
  8721. Blank()
  8722. }
  8723. .margin({
  8724. top: 10,
  8725. bottom: 10,
  8726. right: 20,
  8727. left: 20
  8728. })
  8729. if (isPip) {
  8730. Row() {
  8731. Text(`悬浮背景:`)
  8732. .fontSize(14)
  8733. .fontColor(Color.White)
  8734. Select([
  8735. { value: CommonConstants.PIP_LYRIC_BG[0] },
  8736. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  8737. .font({ size: 13, weight: FontWeight.Medium })
  8738. .fontColor(Color.White)
  8739. .margin({ left: 10 })
  8740. .selected(this.pipBgIndex)
  8741. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  8742. .onSelect(async (_index: number, text?: string | undefined) => {
  8743. this.pipBgIndex = _index
  8744. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  8745. if (this.pipBgIndex === 0) {
  8746. if (this.cover) {
  8747. this.pipBg = this.cover
  8748. } else {
  8749. this.pipBg = this.imageColor
  8750. }
  8751. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8752. } else {
  8753. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8754. }
  8755. })
  8756. Column() {
  8757. }
  8758. .backgroundColor(this.pipBg)
  8759. .margin({ left: 10, right: 10 })
  8760. .borderRadius(20)
  8761. .height(28)
  8762. .width(28)
  8763. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8764. Row() {
  8765. SymbolGlyph($r('sys.symbol.paintbrush'))
  8766. .fontColor([Color.White])
  8767. .effectStrategy(1)
  8768. Text(`选择颜色`)
  8769. .fontSize(13)
  8770. .margin({ left: 10 })
  8771. .fontColor(Color.White)
  8772. }
  8773. }
  8774. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  8775. .backgroundColor(Color.Transparent)
  8776. .border({
  8777. color: '#FFFFFF',
  8778. radius: 20,
  8779. width: 1.8
  8780. })
  8781. .height(36)
  8782. .width(110)
  8783. .onClick(() => {
  8784. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  8785. })
  8786. .bindPopup(this.isShowPipBgSelectColor, {
  8787. builder: this.SelectColor(false, isPip, true),
  8788. placement: Placement.Top,
  8789. mask: { color: '#33000000' },
  8790. enableArrow: false, //是否显示箭头
  8791. showInSubWindow: false,
  8792. onStateChange: (e) => {
  8793. if (!e.isVisible) {
  8794. this.isShowPipBgSelectColor = false
  8795. }
  8796. }
  8797. })
  8798. }
  8799. .width('76%')
  8800. .margin({ bottom: 5, right: 45, left: 20 })
  8801. }
  8802. if (!isPip) {
  8803. Row() {
  8804. Text(`高亮居中:`)
  8805. .fontSize(14)
  8806. .fontColor(Color.White)
  8807. Column() {
  8808. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  8809. .selectedColor(this.themeColor)
  8810. .switchPointColor(Color.White)
  8811. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8812. .onChange((checked: boolean) => {
  8813. this.isHightLightCenter = checked;
  8814. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  8815. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8816. })
  8817. .width(50)
  8818. .height(30)
  8819. .alignSelf(ItemAlign.Start)
  8820. .margin({ left: 12 })
  8821. Blank()
  8822. }
  8823. .width('76%')
  8824. }
  8825. .margin({
  8826. left: 20,
  8827. right: 15,
  8828. top: 10,
  8829. bottom: 10
  8830. })
  8831. }
  8832. Row() {
  8833. Text(`歌词颜色:`)
  8834. .fontSize(14)
  8835. .fontColor(Color.White)
  8836. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8837. .fontSize(15)
  8838. .fontColor(Color.White)
  8839. .margin({ left: 12, right: 12 })
  8840. Column() {
  8841. }
  8842. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8843. .margin({ right: 12 })
  8844. .borderRadius(20)
  8845. .height(28)
  8846. .width(28)
  8847. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8848. Row() {
  8849. SymbolGlyph($r('sys.symbol.paintbrush'))
  8850. .fontColor([Color.White])
  8851. .effectStrategy(1)
  8852. Text(`选择颜色`)
  8853. .fontSize(13)
  8854. .margin({ left: 10 })
  8855. .fontColor(Color.White)
  8856. }
  8857. }
  8858. .backgroundColor(Color.Transparent)
  8859. .border({
  8860. color: '#FFFFFF',
  8861. radius: 20,
  8862. width: 1.8
  8863. })
  8864. .height(36)
  8865. .width(110)
  8866. .onClick(() => {
  8867. this.isShowSelectColor = !this.isShowSelectColor
  8868. })
  8869. .bindPopup(this.isShowSelectColor, {
  8870. builder: this.SelectColor(false, isPip),
  8871. placement: Placement.Top,
  8872. mask: { color: '#33000000' },
  8873. enableArrow: false, //是否显示箭头
  8874. showInSubWindow: false,
  8875. onStateChange: (e) => {
  8876. if (!e.isVisible) {
  8877. this.isShowSelectColor = false
  8878. }
  8879. }
  8880. })
  8881. }
  8882. .width('76%')
  8883. .margin({
  8884. top: 10,
  8885. bottom: 10,
  8886. right: 45,
  8887. left: 20
  8888. })
  8889. Row() {
  8890. Text(`高亮颜色:`)
  8891. .fontSize(14)
  8892. .fontColor(Color.White)
  8893. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8894. .fontSize(15)
  8895. .fontColor(Color.White)
  8896. .margin({ left: 12, right: 12 })
  8897. Column() {
  8898. }
  8899. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8900. .margin({ right: 12 })
  8901. .borderRadius(20)
  8902. .height(28)
  8903. .width(28)
  8904. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8905. Row() {
  8906. SymbolGlyph($r('sys.symbol.paintbrush'))
  8907. .fontColor([Color.White])
  8908. .effectStrategy(1)
  8909. Text(`选择颜色`)
  8910. .fontSize(13)
  8911. .margin({ left: 10 })
  8912. .fontColor(Color.White)
  8913. }
  8914. }
  8915. .backgroundColor(Color.Transparent)
  8916. .border({
  8917. color: '#FFFFFF',
  8918. radius: 20,
  8919. width: 1.8
  8920. })
  8921. .height(36)
  8922. .width(110)
  8923. .onClick(() => {
  8924. this.isShowHLSelectColor = !this.isShowHLSelectColor
  8925. })
  8926. .bindPopup(this.isShowHLSelectColor, {
  8927. builder: this.SelectColor(true, isPip),
  8928. placement: Placement.Top,
  8929. mask: { color: '#33000000' },
  8930. enableArrow: false, //是否显示箭头
  8931. showInSubWindow: false,
  8932. onStateChange: (e) => {
  8933. if (!e.isVisible) {
  8934. this.isShowHLSelectColor = false
  8935. }
  8936. }
  8937. })
  8938. }
  8939. .width('76%')
  8940. .margin({
  8941. top: 10,
  8942. bottom: 10,
  8943. right: 45,
  8944. left: 20
  8945. })
  8946. if (isPip) {
  8947. Row() {
  8948. Text(`显示宽度:`)
  8949. .fontSize(14)
  8950. .fontColor(Color.White)
  8951. Slider({
  8952. value: this.pipLyWidth,
  8953. min: 10,
  8954. max: 800,
  8955. step: 1,
  8956. style: SliderStyle.OutSet
  8957. })
  8958. .blockColor(this.themeColor)
  8959. .trackColor($r('app.color.speed_text_color'))
  8960. .selectedColor(Color.White)
  8961. .trackThickness(6)
  8962. .onChange((value: number) => {
  8963. this.pipLyWidth = value
  8964. if (this.pipController) {
  8965. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8966. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  8967. }
  8968. })
  8969. .width('76%')
  8970. }
  8971. .margin({
  8972. left: 20,
  8973. right: 15,
  8974. top: 5,
  8975. bottom: 5
  8976. })
  8977. Row() {
  8978. Text(`显示高度:`)
  8979. .fontSize(14)
  8980. .fontColor(Color.White)
  8981. Slider({
  8982. value: this.pipLyHeight,
  8983. min: 10,
  8984. max: 1000,
  8985. step: 1,
  8986. style: SliderStyle.OutSet
  8987. })
  8988. .blockColor(this.themeColor)
  8989. .trackColor($r('app.color.speed_text_color'))
  8990. .selectedColor(Color.White)
  8991. .trackThickness(6)
  8992. .onChange((value: number) => {
  8993. this.pipLyHeight = value
  8994. if (this.pipController) {
  8995. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8996. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  8997. }
  8998. })
  8999. .width('76%')
  9000. }
  9001. .margin({
  9002. left: 20,
  9003. right: 15,
  9004. top: 5,
  9005. bottom: 5
  9006. })
  9007. }
  9008. Row() {
  9009. Text(`歌词字号:`)
  9010. .fontSize(14)
  9011. .fontColor(Color.White)
  9012. Slider({
  9013. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  9014. min: 12,
  9015. max: 30,
  9016. step: 0.1,
  9017. style: SliderStyle.OutSet
  9018. })
  9019. .blockColor(this.themeColor)
  9020. .trackColor($r('app.color.speed_text_color'))
  9021. .selectedColor(Color.White)
  9022. .trackThickness(6)
  9023. .onChange((value: number) => {
  9024. this.setLyricTextSize(value, isPip)
  9025. })
  9026. .width('76%')
  9027. }
  9028. .margin({
  9029. left: 20,
  9030. right: 15,
  9031. top: 5,
  9032. bottom: 5
  9033. })
  9034. Row() {
  9035. Text(`高亮倍数:`)
  9036. .fontSize(14)
  9037. .fontColor(Color.White)
  9038. Slider({
  9039. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  9040. min: 1,
  9041. max: 2,
  9042. step: 0.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.setHighLyricTextSize(value, isPip)
  9051. })
  9052. .width('76%')
  9053. }
  9054. .margin({
  9055. left: 20,
  9056. right: 15,
  9057. top: 5,
  9058. bottom: 5
  9059. })
  9060. Row() {
  9061. Text(`歌词间隙:`)
  9062. .fontSize(14)
  9063. .fontColor(Color.White)
  9064. Slider({
  9065. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  9066. min: 0,
  9067. max: 100,
  9068. step: 1,
  9069. style: SliderStyle.OutSet
  9070. })
  9071. .blockColor(this.themeColor)
  9072. .trackColor($r('app.color.speed_text_color'))
  9073. .selectedColor(Color.White)
  9074. .trackThickness(6)
  9075. .onChange((value: number) => {
  9076. this.setLyricLineSpace(value, isPip)
  9077. })
  9078. .width('76%')
  9079. }
  9080. .margin({
  9081. left: 20,
  9082. right: 15,
  9083. top: 5,
  9084. bottom: 5
  9085. })
  9086. //取值间隔为100,默认为400,取值越大,字体越粗
  9087. Row() {
  9088. Text(`歌词字重:`)
  9089. .fontSize(14)
  9090. .fontColor(Color.White)
  9091. Slider({
  9092. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  9093. min: 100,
  9094. max: 900,
  9095. step: 100,
  9096. style: SliderStyle.OutSet
  9097. })
  9098. .blockColor(this.themeColor)
  9099. .trackColor($r('app.color.speed_text_color'))
  9100. .selectedColor(Color.White)
  9101. .trackThickness(6)
  9102. .onChange((value: number) => {
  9103. if (isPip) {
  9104. this.lyricTextWeightPip = value
  9105. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9106. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  9107. } else {
  9108. this.lyricTextWeight = value
  9109. this.lyricController.setTextWeight(this.lyricTextWeight)
  9110. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  9111. }
  9112. })
  9113. .width('76%')
  9114. }
  9115. .margin({
  9116. left: 20,
  9117. right: 15,
  9118. top: 5,
  9119. bottom: 5
  9120. })
  9121. if (!isPip) {
  9122. Row() {
  9123. Text(`歌词模糊:`)
  9124. .fontSize(14)
  9125. .fontColor(Color.White)
  9126. Slider({
  9127. value: isPip ? this.blurDegreePip : this.blurDegree,
  9128. min: 0,
  9129. max: 5,
  9130. step: 0.1,
  9131. style: SliderStyle.OutSet
  9132. })
  9133. .blockColor(this.themeColor)
  9134. .trackColor($r('app.color.speed_text_color'))
  9135. .selectedColor(Color.White)
  9136. .trackThickness(6)
  9137. .onChange((value: number) => {
  9138. this.setBlurDegree(value, isPip)
  9139. })
  9140. .width('76%')
  9141. }
  9142. .margin({
  9143. left: 20,
  9144. right: 15,
  9145. top: 5,
  9146. bottom: 15
  9147. })
  9148. }
  9149. Row() {
  9150. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  9151. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  9152. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  9153. }
  9154. .justifyContent(FlexAlign.Center)
  9155. .margin({ top: 3, bottom: 10 })
  9156. }
  9157. }
  9158. private setBlurDegree(index: number, isPip: boolean) {
  9159. if (isPip) {
  9160. this.blurDegreePip = index
  9161. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  9162. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  9163. } else {
  9164. this.blurDegree = index
  9165. this.lyricController.setBlurDegree(this.blurDegree)
  9166. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  9167. }
  9168. }
  9169. private setLyricAlignMode(index: number, isPip: boolean) {
  9170. if (isPip) {
  9171. this.currentLyricAlignModePip = index
  9172. if (this.currentLyricAlignModePip === 1) {
  9173. this.lyricControllerXF.setAlignMode("left")
  9174. } else {
  9175. this.lyricControllerXF.setAlignMode("center")
  9176. }
  9177. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  9178. } else {
  9179. this.currentLyricAlignMode = index
  9180. if (this.currentLyricAlignMode === 1) {
  9181. this.lyricController.setAlignMode("left")
  9182. } else {
  9183. this.lyricController.setAlignMode("center")
  9184. }
  9185. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  9186. }
  9187. }
  9188. private setLyricTextSize(index: number, isPip: boolean) {
  9189. if (isPip) {
  9190. this.currentLyricSizePip = index
  9191. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  9192. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  9193. } else {
  9194. this.currentLyricSize = index
  9195. this.lyricController.setTextSize(this.currentLyricSize)
  9196. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  9197. }
  9198. }
  9199. private setHighLyricTextSize(scale: number, isPip: boolean) {
  9200. if (isPip) {
  9201. this.currentHightLyricSizePip = scale
  9202. this.lyricControllerXF
  9203. .setHighlightScale(this.currentHightLyricSizePip)
  9204. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  9205. } else {
  9206. this.currentHightLyricSize = scale
  9207. this.lyricController
  9208. .setHighlightScale(this.currentHightLyricSize)
  9209. PreferencesUtil.putSync('HighLyricTextSize', scale)
  9210. }
  9211. }
  9212. private setLyricLineSpace(index: number, isPip: boolean) {
  9213. if (isPip) {
  9214. this.currentLyricLineSpacePip = index
  9215. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  9216. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  9217. } else {
  9218. this.currentLyricLineSpace = index
  9219. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  9220. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  9221. }
  9222. }
  9223. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  9224. LogUtil.info('onecold isBG = ' + isBG)
  9225. if (isBG) { //如果是设置悬浮背景
  9226. this.pipBg = color
  9227. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  9228. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9229. return
  9230. }
  9231. if (isPip) {
  9232. this.currentLyricColorPip = color
  9233. this.lyricControllerXF
  9234. .setTextColor(this.currentLyricColorPip)
  9235. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  9236. } else {
  9237. this.currentLyricColor = color
  9238. this.lyricController
  9239. .setTextColor(this.currentLyricColor)
  9240. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  9241. }
  9242. }
  9243. private changeLyricHightLightColor(color: string, isPip: boolean) {
  9244. if (isPip) {
  9245. this.currentHighLightLyricColorPip = color
  9246. this.lyricControllerXF
  9247. .setHighlightColor(this.currentHighLightLyricColorPip)
  9248. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  9249. } else {
  9250. this.currentHighLightLyricColor = color
  9251. this.lyricController
  9252. .setHighlightColor(this.currentHighLightLyricColor)
  9253. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  9254. }
  9255. }
  9256. // 构建时间控制器
  9257. @Builder
  9258. BuildTimeControls() {
  9259. Column() {
  9260. // 时间显示
  9261. Text(this.getTimeText())
  9262. .fontSize(18)
  9263. .fontColor(Color.White)
  9264. .margin({ bottom: 10 })
  9265. Row() {
  9266. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  9267. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  9268. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  9269. }
  9270. .justifyContent(FlexAlign.Center)
  9271. }
  9272. .margin({ top: 12, bottom: 8 })
  9273. }
  9274. // 精度按钮组件
  9275. @Builder
  9276. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  9277. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9278. Column() {
  9279. Image(icon)
  9280. .width(28)
  9281. .margin({ bottom: 5 })
  9282. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  9283. Text(label)
  9284. .fontSize(12)
  9285. .fontColor('#FFFFFF')
  9286. }
  9287. }
  9288. .backgroundColor(Color.Transparent)
  9289. .enabled(!this.isButtonDisabled(step))
  9290. .onClick(() => this.handlePrecisionAdjust(step))
  9291. .padding(5)
  9292. .width(66)
  9293. .height(66)
  9294. .margin({ left: 18, right: 18 })
  9295. .border({
  9296. color: '#FFFFFF',
  9297. width: 1.8
  9298. })
  9299. }
  9300. private handlePrecisionAdjust(step: number) {
  9301. if (step === 0) {
  9302. this.timeOffset = 0
  9303. return
  9304. }
  9305. // 精度处理:保留1位小数
  9306. const newOffset = Number((this.timeOffset + step).toFixed(5))
  9307. // 边界保护(±15.0秒)
  9308. if (newOffset < -30.0 || newOffset > 30.0) {
  9309. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  9310. return
  9311. }
  9312. // 状态更新
  9313. this.timeOffset = newOffset
  9314. }
  9315. // 按钮禁用逻辑
  9316. private isButtonDisabled(step: number): boolean {
  9317. const futureOffset = this.timeOffset + step
  9318. return (futureOffset < -30.0) || (futureOffset > 30.0)
  9319. }
  9320. // 时间显示文本升级
  9321. private getTimeText(): string {
  9322. const absValue = Math.abs(this.timeOffset)
  9323. return this.timeOffset === 0
  9324. ? '歌词时间已重置'
  9325. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  9326. }
  9327. // 导入 本地歌词 搜索歌词
  9328. @Builder
  9329. pushLyricButton(icon: Resource, step: number, label: string) {
  9330. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9331. Row() {
  9332. Image(icon)
  9333. .width(14)
  9334. .margin({ left: 13 })
  9335. Text(label)
  9336. .fontSize(12)
  9337. .margin({ left: 6 })
  9338. .fontColor('#FFFFFF')
  9339. }
  9340. }
  9341. .onClick(() => {
  9342. switch (step) {
  9343. case 0:
  9344. this.callFilePickerSelectFileForLyric()
  9345. break;
  9346. case 1:
  9347. //判断有没有设置api
  9348. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  9349. this.isLyricSetting = false
  9350. this.showTipsDialog()
  9351. return
  9352. }
  9353. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9354. ToastUtil.showToast('正在获取')
  9355. this.isLyricSetting = false
  9356. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9357. this.initLyric(lyricPath, true);
  9358. }
  9359. break;
  9360. }
  9361. })
  9362. .padding(5)
  9363. .width(110)
  9364. .backgroundColor(Color.Transparent)
  9365. .height(40)
  9366. .margin({ left: 6, right: 6 })
  9367. .border({
  9368. color: '#FFFFFF',
  9369. radius: 20,
  9370. width: 1.8
  9371. })
  9372. }
  9373. showVipDialog() {
  9374. DialogHelper.showCustomContentDialog({
  9375. dialogId: 'vip',
  9376. title: "友情提示",
  9377. autoCancel: false, //点击遮障层时,不关闭弹窗
  9378. backCancel: true, //点击返回键,不关闭弹窗
  9379. contentBuilder: () => {
  9380. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  9381. },
  9382. buttons: [],
  9383. })
  9384. }
  9385. //去赞助的自定义内容
  9386. @Builder
  9387. customVipBuilder(content: string) {
  9388. Column() {
  9389. Text(content)
  9390. .fontColor(Color.Gray)
  9391. .fontSize(16)
  9392. .alignSelf(ItemAlign.Start)
  9393. .margin({ bottom: 15 })
  9394. .fontSize(16)
  9395. Row() {
  9396. Button('取消')
  9397. .fontColor(Color.White)
  9398. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9399. .height(50)
  9400. .layoutWeight(1)
  9401. .stateEffect(true)
  9402. .margin({ right: 6 })
  9403. .onClick(() => {
  9404. DialogHelper.closeDialog('vip'); //关闭弹框
  9405. })
  9406. Button('开通')
  9407. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9408. .layoutWeight(1)
  9409. .height(50)
  9410. .backgroundColor(this.themeColor)
  9411. .stateEffect(true)
  9412. .margin({ left: 6 })
  9413. .onClick(() => {
  9414. DialogHelper.closeDialog('vip'); //关闭弹框
  9415. this.isShowPlay = false
  9416. this.mType = 1 //跳转到用户中心
  9417. // router.pushUrl({
  9418. // url: 'pages/VipPage'
  9419. // }, router.RouterMode.Single);
  9420. })
  9421. }
  9422. }
  9423. .width("100%")
  9424. .padding(10)
  9425. }
  9426. showTipsDialog() {
  9427. DialogHelper.showCustomContentDialog({
  9428. dialogId: 'tips',
  9429. title: "友情提示",
  9430. autoCancel: false, //点击遮障层时,不关闭弹窗
  9431. backCancel: true, //点击返回键,不关闭弹窗
  9432. contentBuilder: () => {
  9433. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  9434. },
  9435. buttons: [],
  9436. })
  9437. }
  9438. @Builder
  9439. customTipsBuilder(content: string) {
  9440. Column() {
  9441. Text(content)
  9442. .fontColor(Color.Gray)
  9443. .fontSize(16)
  9444. .alignSelf(ItemAlign.Start)
  9445. .margin({ bottom: 15 })
  9446. .fontSize(16)
  9447. Row() {
  9448. Button('取消')
  9449. .fontColor(Color.White)
  9450. .backgroundColor(this.themeColor)
  9451. .height(50)
  9452. .layoutWeight(1)
  9453. .stateEffect(true)
  9454. .margin({ right: 6 })
  9455. .onClick(() => {
  9456. DialogHelper.closeDialog('tips'); //关闭弹框
  9457. })
  9458. Button('跳转')
  9459. .fontColor(Color.White)//
  9460. .layoutWeight(1)
  9461. .height(50)
  9462. .backgroundColor(this.themeColor)
  9463. .stateEffect(true)
  9464. .margin({ left: 6 })
  9465. .onClick(() => {
  9466. DialogHelper.closeDialog('tips'); //关闭弹框
  9467. this.isShowEdit = false
  9468. this.longItemFilePath = ''
  9469. // if(this.isGridMusic&&!this.isShowPlay){
  9470. // this.longItemFilePath== ''
  9471. // }else{
  9472. // this.isShowEdit = false
  9473. // }
  9474. this.isShowMoreView = false;
  9475. this.isShowPlay = false
  9476. this.mType = 4
  9477. // router.pushUrl({
  9478. // url: 'pages/SettingPage'
  9479. // }, router.RouterMode.Single);
  9480. })
  9481. }
  9482. }
  9483. .width("100%")
  9484. .padding(10)
  9485. }
  9486. @Builder
  9487. PlayMoreSheet() {
  9488. Column() {
  9489. this.MoreList()
  9490. }
  9491. .width('100%')
  9492. .height('100%')
  9493. }
  9494. @Builder
  9495. MoreList() {
  9496. Scroll() {
  9497. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9498. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  9499. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9500. Row() {
  9501. if (more.id === 3&&this.currentSong) {
  9502. Image(more.image)
  9503. .width(24)
  9504. .height(24)
  9505. .margin({ left: 10, right: 10 })
  9506. Text(more.title)
  9507. .fontSize(16)
  9508. .fontColor(Color.White)
  9509. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  9510. height: this.isCoverOpacity() ? '95%' : '95%',
  9511. dragBar: true,
  9512. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9513. showClose: true,
  9514. blurStyle: BlurStyle.Thin,
  9515. backgroundColor: Color.Transparent,
  9516. title: { title: '歌曲信息' }
  9517. })
  9518. } else if (more.id === 15 && this.currentSong) { //编辑标签
  9519. Image(more.image)
  9520. .width(24)
  9521. .height(24)
  9522. .margin({ left: 10, right: 10 })
  9523. Text(more.title)
  9524. .fontSize(16)
  9525. .fontColor(Color.White)
  9526. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9527. height: '99%',
  9528. dragBar: true,
  9529. showClose: true,
  9530. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9531. // blurStyle:BlurStyle.Thin,
  9532. // backgroundColor:Color.Transparent,
  9533. title: { title: '编辑标签' }
  9534. })
  9535. } else if (more.id === 5) { //定时关闭
  9536. Image(more.image)
  9537. .width(24)
  9538. .height(24)
  9539. .margin({ left: 10, right: 10 })
  9540. Text(more.title)
  9541. .fontSize(16)
  9542. .fontColor(Color.White)
  9543. .onClick(() => {
  9544. this.doMore(more.id)
  9545. })
  9546. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  9547. height: this.isCoverOpacity() ? '95%' : '95%',
  9548. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9549. dragBar: true,
  9550. showClose: true,
  9551. title: { title: $r('app.string.time_close') }
  9552. })
  9553. } else if (more.id === 2) { //歌词设置
  9554. Image(more.image)
  9555. .width(24)
  9556. .height(24)
  9557. .margin({ left: 10, right: 10 })
  9558. Text(more.title)
  9559. .fontSize(16)
  9560. .fontColor(Color.White)
  9561. } else if (more.id === 16) { //悬浮歌词设置
  9562. Image(more.image)
  9563. .width(24)
  9564. .height(24)
  9565. .margin({ left: 10, right: 10 })
  9566. Text(more.title)
  9567. .fontSize(16)
  9568. .fontColor(Color.White)
  9569. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  9570. height: this.isCoverOpacity() ? '95%' : '95%',
  9571. dragBar: true,
  9572. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9573. showClose: true,
  9574. blurStyle: BlurStyle.Thin,
  9575. backgroundColor: Color.Transparent,
  9576. title: { title: '悬浮歌词' }
  9577. })
  9578. } else if (more.id === 11) {
  9579. Image(more.image)
  9580. .width(24)
  9581. .height(24)
  9582. .margin({ left: 10, right: 10 })
  9583. Text(more.title)
  9584. .fontSize(16)
  9585. .fontColor(Color.White)
  9586. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  9587. height: this.isCoverOpacity() ? '95%' : '60%',
  9588. dragBar: true,
  9589. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9590. showClose: true,
  9591. blurStyle: BlurStyle.Thin,
  9592. backgroundColor: Color.Transparent,
  9593. title: { title: '跳过头尾' }
  9594. })
  9595. } else if (more.id === 12) { //投播
  9596. AVCastPicker({
  9597. customPicker: (): void => this.TPImageBuilder(more),
  9598. onStateChange: (state) => {
  9599. if (state == AVCastPickerState.STATE_APPEARING) {
  9600. console.log(' The picker starts showing.');
  9601. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  9602. console.log(' The picker finishes presenting.');
  9603. }
  9604. },
  9605. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  9606. sessionType: 'video'
  9607. })
  9608. .id('AVCastPicker')
  9609. } else {
  9610. Image(more.image)
  9611. .width(24)
  9612. .height(24)
  9613. .margin({ left: 10, right: 10 })
  9614. .onClick(() => {
  9615. this.doMore(more.id)
  9616. })
  9617. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  9618. .fontSize(16)
  9619. .fontColor(Color.White)
  9620. .onClick(() => {
  9621. this.doMore(more.id)
  9622. })
  9623. Select([//倍速
  9624. { value: '0.25x' },
  9625. { value: '0.5x' },
  9626. { value: '0.75x' },
  9627. { value: '1x' },
  9628. { value: '1.25x' },
  9629. { value: '1.5x' },
  9630. { value: '1.75x' },
  9631. { value: '2x' },
  9632. { value: '3x' }])
  9633. .font({ size: 16, weight: FontWeight.Medium })
  9634. .fontColor($r('sys.color.white'))
  9635. .margin({ left: 25 })
  9636. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  9637. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  9638. .value(Utility.optimizedFormat(this.playSpeed))
  9639. .onSelect(async (_index: number, text?: string | undefined) => {
  9640. let speed = parseFloat(text?.replace('x', '') || '1');
  9641. if (!CommonConstants.video_speed_list.includes(speed)) {
  9642. speed = 1;
  9643. }
  9644. this.playSpeed = speed
  9645. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9646. })
  9647. Slider({
  9648. value: this.volume,
  9649. min: 0,
  9650. max: 1,
  9651. step: 0.1,
  9652. style: SliderStyle.OutSet
  9653. })
  9654. .margin({ left: 18, right: 8 })
  9655. .blockColor(this.themeColor)
  9656. .trackColor($r('app.color.speed_text_color'))
  9657. .selectedColor(Color.White)
  9658. .trackThickness(9)
  9659. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  9660. .onChange((value: number) => {
  9661. this.volume = value;
  9662. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9663. PreferencesUtil.putSync('DefalutVolume',this.volume)
  9664. })
  9665. .layoutWeight(1)
  9666. Blank()
  9667. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  9668. .selectedColor(this.themeColor)
  9669. .switchPointColor(Color.White)
  9670. .margin({ right: 15 })
  9671. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9672. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  9673. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9674. if (more.id == 6) {
  9675. this.isMusicMemoryPlay = checked;
  9676. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  9677. if (this.isMusicMemoryPlay) {
  9678. ToastUtil.showToast('记忆播放已开启')
  9679. } else {
  9680. ToastUtil.showToast('记忆播放已关闭')
  9681. }
  9682. }
  9683. })
  9684. .width(48)
  9685. .height(24);
  9686. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  9687. .selectedColor(this.themeColor)
  9688. .switchPointColor(Color.White)
  9689. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9690. .margin({ right: 15 })
  9691. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  9692. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9693. if (more.id == 7) {
  9694. this.isMusicBGCover = checked;
  9695. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  9696. if (this.isMusicBGCover) {
  9697. ToastUtil.showToast('播放背景随音乐封面已开启')
  9698. } else {
  9699. ToastUtil.showToast('播放背景随音乐封面已关闭')
  9700. }
  9701. }
  9702. })
  9703. .width(48)
  9704. .height(24);
  9705. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  9706. .selectedColor(this.themeColor)
  9707. .switchPointColor(Color.White)
  9708. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9709. .margin({ right: 15 })
  9710. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  9711. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9712. if (more.id == 8) {
  9713. this.isSavePlayMode = checked;
  9714. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  9715. if (this.isSavePlayMode) {
  9716. ToastUtil.showToast('保存播放模式已开启')
  9717. } else {
  9718. ToastUtil.showToast('保存播放模式已关闭')
  9719. }
  9720. }
  9721. })
  9722. .width(48)
  9723. .height(24);
  9724. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  9725. .selectedColor(this.themeColor)
  9726. .switchPointColor(Color.White)
  9727. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9728. .margin({ right: 15 })
  9729. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  9730. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9731. if (more.id == 13) {
  9732. this.isCoverRectangle = checked;
  9733. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  9734. if (this.isCoverRectangle) {
  9735. ToastUtil.showToast('封面方形已开启')
  9736. this.animationRoFun()
  9737. } else {
  9738. ToastUtil.showToast('封面圆形已开启')
  9739. this.animationRoFun()
  9740. }
  9741. }
  9742. })
  9743. .width(48)
  9744. .height(24);
  9745. }
  9746. }
  9747. .width('100%')
  9748. .height(45)
  9749. .padding(15)
  9750. .backgroundColor(Color.Transparent)
  9751. .borderRadius(12)
  9752. .margin({ bottom: 6 })
  9753. }
  9754. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  9755. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  9756. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  9757. .backgroundColor(Color.Transparent)
  9758. .onClick(() => {
  9759. this.doMore(more.id)
  9760. })
  9761. });
  9762. }
  9763. .width('100%')
  9764. .padding(16)
  9765. }.margin({ bottom: 18 })
  9766. }
  9767. @Builder
  9768. TPImageBuilder(more: MoreItem): void {
  9769. Row() {
  9770. Image($r('app.media.tuoping'))
  9771. .width(22)
  9772. .height(22)
  9773. .margin({ left: 10, right: 10 })
  9774. Text(more.title)
  9775. .fontSize(16)
  9776. .fontColor(Color.White)
  9777. }
  9778. .width('100%')
  9779. .layoutWeight(1)
  9780. .alignItems(VerticalAlign.Center)
  9781. .justifyContent(FlexAlign.Start)
  9782. }
  9783. private moreItems: MoreItem[] = [
  9784. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  9785. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  9786. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  9787. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  9788. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  9789. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  9790. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  9791. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  9792. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  9793. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  9794. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  9795. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  9796. { id: 4, image: $r('app.media.share2'), title: '分享' },
  9797. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  9798. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  9799. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  9800. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  9801. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  9802. ];
  9803. @State isShowMoreView: boolean = false;
  9804. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  9805. @State isShowTimeCloseMore: boolean = false
  9806. @State isShowDetailMore: boolean = false
  9807. @State isMusicBGCover: boolean = true
  9808. @State isSavePlayMode: boolean = true
  9809. @State isLyricSetting: boolean = false
  9810. @State isJumpSetting: boolean = false
  9811. @State isShowEdit: boolean = false
  9812. @State showPipLyric: boolean = false
  9813. async setRingTone() {
  9814. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  9815. return
  9816. }
  9817. // 确定后的逻辑
  9818. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  9819. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  9820. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  9821. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  9822. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  9823. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  9824. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  9825. , this.videoUrl, this.name).then(res => {
  9826. LogUtil.info('onecold setFlag :' + res);
  9827. });
  9828. }
  9829. doMore(moreId: number) {
  9830. switch (moreId) {
  9831. case 2: //歌词
  9832. this.isLyricSetting = !this.isLyricSetting;
  9833. this.isShowMoreView = false
  9834. break;
  9835. case 3: //详情
  9836. this.isShowDetailMore = !this.isShowDetailMore;
  9837. break;
  9838. case 4: //分享
  9839. if (this.currentSong !== undefined) {
  9840. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  9841. }
  9842. this.isShowMoreView = false
  9843. break;
  9844. case 5: //定时关闭
  9845. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  9846. break;
  9847. case 10: //设为铃声
  9848. this.setRingTone()
  9849. this.isShowMoreView = false
  9850. break;
  9851. case 11: //跳过头尾
  9852. this.isJumpSetting = !this.isJumpSetting;
  9853. break;
  9854. case 13: //倍速
  9855. break;
  9856. case 14: //搜索封面
  9857. if (this.currentSong !== undefined) {
  9858. this.doSearchCover(this.currentSong)
  9859. }
  9860. this.isShowMoreView = false
  9861. break;
  9862. case 15: //编辑标签
  9863. this.setEditStrEmpty()
  9864. this.tempLyricContent = this.lyricContent
  9865. this.isShowEdit = !this.isShowEdit;
  9866. break;
  9867. case 16: //悬浮歌词
  9868. this.showPipLyric = !this.showPipLyric;
  9869. break;
  9870. case 17: //横屏模式
  9871. if (this.isLandscape) {
  9872. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9873. } else {
  9874. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9875. }
  9876. this.isShowMoreView = false
  9877. break;
  9878. case 20://AB循环
  9879. this.isOpenAB = !this.isOpenAB;
  9880. this.isABSheet = false
  9881. break;
  9882. }
  9883. }
  9884. //AB循环
  9885. @State isOpenAB:boolean = false
  9886. @State jumpATime:number = 0
  9887. @State jumpBTime:number = 0
  9888. @State isABSheet:boolean = false
  9889. @Builder
  9890. ABLoopSheet() {
  9891. ABLoopComptent({
  9892. jumpATime:this.jumpATime,
  9893. jumpBTime:this.jumpBTime,
  9894. onClickAItem: async ()=>{
  9895. if(this.mIjkMediaPlayer){
  9896. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  9897. }
  9898. },
  9899. onClickBItem: async ()=>{
  9900. if(this.mIjkMediaPlayer){
  9901. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  9902. if(this.jumpBTime<=this.jumpATime){
  9903. ToastUtil.showToast('设置B点时间不能小于A点时间')
  9904. this.jumpBTime = 0
  9905. }
  9906. }
  9907. },
  9908. onCancleButtonClick: async ()=>{
  9909. this.isOpenAB = false
  9910. this.isABSheet = false
  9911. },
  9912. onStartButtonClick: async ()=>{
  9913. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  9914. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  9915. return
  9916. }
  9917. this.isABSheet = false
  9918. this.startABLoop()
  9919. },
  9920. })
  9921. }
  9922. //开始AB循环
  9923. startABLoop(){
  9924. if(this.mIjkMediaPlayer){
  9925. this.seekTo(this.jumpATime+'')
  9926. this.isOpenAB = true
  9927. }
  9928. }
  9929. /**
  9930. * 切换横竖屏
  9931. *
  9932. */
  9933. setOrientation(orientation: number) {
  9934. this.windowClass.setPreferredOrientation(orientation).then(() => {
  9935. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  9936. }).catch((err: BusinessError) => {
  9937. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  9938. });
  9939. }
  9940. /**
  9941. * 画中画功能(悬浮歌词功能)
  9942. *
  9943. */
  9944. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  9945. pipController?: PiPWindow.PiPController;
  9946. navigationId: string = '';
  9947. @State curState: string = '';
  9948. @State curError: ResourceStr = '';
  9949. @State pipBg: string = '#E8E8E8'
  9950. @State buttonAction: string = '';
  9951. //开启画中画功能
  9952. async startPip() {
  9953. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  9954. if (!this.pipController) {
  9955. await this.createPipController();
  9956. }
  9957. if (!this.pipController) {
  9958. Logger.info(`[${TAG}] pipController create error`);
  9959. return;
  9960. }
  9961. await this.pipController.startPiP();
  9962. }
  9963. async stopPip() {
  9964. if (!this.pipController) {
  9965. Logger.info(`[${TAG}] pipController is not exist`);
  9966. return;
  9967. }
  9968. this.isOpenPip = false
  9969. await this.pipController.stopPiP();
  9970. }
  9971. async createPipController() {
  9972. this.pipController = await PiPWindow.create({
  9973. context: getContext(this),
  9974. componentController: this.xcomponentController,
  9975. navigationId: this.navigationId,
  9976. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  9977. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  9978. customUIController: this.nodeController,
  9979. });
  9980. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  9981. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  9982. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9983. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  9984. this.onStateChange(state, reason);
  9985. });
  9986. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  9987. this.onActionEvent(event, status);
  9988. });
  9989. }
  9990. destroyPipController() {
  9991. if (!this.pipController) {
  9992. return;
  9993. }
  9994. this.pipController.off('stateChange');
  9995. this.pipController.off('controlPanelActionEvent');
  9996. this.pipController = undefined;
  9997. }
  9998. onStateChange(state: PiPWindow.PiPState, reason: string) {
  9999. switch (state) {
  10000. case PiPWindow.PiPState.ABOUT_TO_START:
  10001. this.curState = 'ABOUT_TO_START';
  10002. this.curError = $r('app.string.current_error_hint');
  10003. break;
  10004. case PiPWindow.PiPState.STARTED:
  10005. this.curState = 'STARTED';
  10006. this.curError = $r('app.string.current_error_hint');
  10007. break;
  10008. case PiPWindow.PiPState.ABOUT_TO_STOP:
  10009. this.curState = 'ABOUT_TO_STOP';
  10010. this.curError = $r('app.string.current_error_hint');
  10011. break;
  10012. case PiPWindow.PiPState.STOPPED:
  10013. this.curState = 'STOPPED';
  10014. this.curError = $r('app.string.current_error_hint');
  10015. this.stopPip()
  10016. this.destroyPipController()
  10017. break;
  10018. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  10019. this.curState = 'ABOUT_TO_RESTORE';
  10020. this.curError = $r('app.string.current_error_hint');
  10021. break;
  10022. case PiPWindow.PiPState.ERROR:
  10023. this.curState = 'ERROR';
  10024. this.curError = reason;
  10025. break;
  10026. default:
  10027. break;
  10028. }
  10029. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  10030. }
  10031. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  10032. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  10033. switch (event) {
  10034. case 'playbackStateChanged':
  10035. if (status === 0) {
  10036. this.pause();
  10037. } else {
  10038. console.info('onecold startPlayOrResumePlay 9869')
  10039. this.startPlayOrResumePlay();
  10040. }
  10041. break;
  10042. case 'nextVideo':
  10043. // 切换到下一个视频
  10044. this.playNext()
  10045. break;
  10046. case 'previousVideo':
  10047. // 切换到上一个视频
  10048. this.playPrevious()
  10049. break;
  10050. case 'previousVideo':
  10051. // 切换到上一个视频
  10052. this.playPrevious()
  10053. break;
  10054. default:
  10055. }
  10056. this.buttonAction = event + `-status:${status}`;
  10057. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  10058. }
  10059. /**
  10060. * 画中画功能(悬浮歌词功能)结束
  10061. *
  10062. */
  10063. async doSearchCover(item: VideoItem): Promise<string> {
  10064. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  10065. this.isShowMoreView = false;
  10066. this.showTipsDialog();
  10067. return ''; // Return empty string when no API is configured
  10068. }
  10069. if (!item) {
  10070. return ''; // Return empty string if item is undefined
  10071. }
  10072. const artist = item?.artist || ''; // Use empty string if artist is missing
  10073. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  10074. }
  10075. /**
  10076. *api搜索封面
  10077. *item,根据title和artist
  10078. */
  10079. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  10080. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  10081. LogUtil.debug("onecold res =" + res);
  10082. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10083. if (item.filePath == this.currentSong?.filePath) {
  10084. this.cover = res;
  10085. if (this.currentSong) {
  10086. this.currentSong.pixelMapPath = res;
  10087. }
  10088. }
  10089. // Update pixel map path but always return res regardless of success
  10090. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  10091. if (success) {
  10092. this.doUpdateData();
  10093. console.log("onecold 更新音乐封面成功,数据库已同步");
  10094. } else {
  10095. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  10096. }
  10097. // Note: We don't resolve/reject here because we already returned res
  10098. });
  10099. LogUtil.debug("onecold this.cover =" + this.cover);
  10100. }
  10101. return res; // Always return res regardless of updatePixelMapPath result
  10102. });
  10103. }
  10104. @State jumpTopTime: number = 0
  10105. @State jumpEndTime: number = 0
  10106. @State isOpenJump: boolean = false
  10107. @Builder
  10108. JumpTopEndSheet() {
  10109. Scroll() {
  10110. Column() {
  10111. Column() {
  10112. Text('仅对本播放列表有效')
  10113. .fontSize(16)
  10114. .fontColor($r('app.color.text_color'))
  10115. // 跳过头尾
  10116. Column() {
  10117. Row() {
  10118. Text('跳过片头:')
  10119. .fontSize(16)
  10120. .fontColor($r('app.color.text_color'))
  10121. Text(this.jumpTopTime + 's')
  10122. .fontSize(16)
  10123. .fontColor($r('app.color.text_color'))
  10124. }
  10125. .margin({ bottom: 5 })
  10126. Row() {
  10127. Slider({
  10128. value: this.jumpTopTime,
  10129. min: 0,
  10130. max: 120,
  10131. step: 1,
  10132. style: SliderStyle.OutSet
  10133. })
  10134. .blockColor(this.themeColor)
  10135. .trackColor($r('app.color.speed_text_color'))
  10136. .selectedColor(Color.White)
  10137. .trackThickness(8)
  10138. .onChange((value: number) => {
  10139. this.jumpTopTime = value;
  10140. })
  10141. .width('85%')
  10142. }
  10143. .alignItems(VerticalAlign.Top)
  10144. }
  10145. .margin({ top: 10, bottom: 10 })
  10146. // 跳过头尾
  10147. Column() {
  10148. Row() {
  10149. Text('跳过片尾:')
  10150. .fontSize(16)
  10151. .fontColor($r('app.color.text_color'))
  10152. Text(this.jumpEndTime + 's')
  10153. .fontSize(16)
  10154. .fontColor($r('app.color.text_color'))
  10155. }
  10156. .margin({ bottom: 5 })
  10157. Row() {
  10158. Slider({
  10159. value: this.jumpEndTime,
  10160. min: 0,
  10161. max: 120,
  10162. step: 1,
  10163. style: SliderStyle.OutSet
  10164. })
  10165. .blockColor(this.themeColor)
  10166. .trackColor($r('app.color.speed_text_color'))
  10167. .selectedColor(Color.White)
  10168. .trackThickness(8)
  10169. .onChange((value: number) => {
  10170. this.jumpEndTime = value;
  10171. })
  10172. .width('85%')
  10173. }
  10174. .alignItems(VerticalAlign.Top)
  10175. }
  10176. .margin({ top: 10, bottom: 10 })
  10177. Row() {
  10178. Button('保存设置')
  10179. .fontColor(Color.White)
  10180. .layoutWeight(1)
  10181. .height(40)
  10182. .width(80)
  10183. .backgroundColor(this.themeColor)
  10184. .stateEffect(true)
  10185. .margin({ left: 0, bottom: 20 })
  10186. .onClick(async () => {
  10187. if (!Utility.isNoble()) {
  10188. this.isJumpSetting = false
  10189. this.isShowMoreView = false
  10190. this.showVipDialog()
  10191. return
  10192. }
  10193. if (this.currentSong === undefined) {
  10194. return
  10195. }
  10196. if (this.modeType === 0) {
  10197. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10198. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  10199. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  10200. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  10201. } else if (this.modeType === 1) { //媒体库
  10202. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  10203. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  10204. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  10205. } else if (this.modeType === 2) { //艺术家
  10206. if (this.currentSong?.artist) {
  10207. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  10208. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  10209. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  10210. }
  10211. } else if (this.modeType === 3) { //专辑
  10212. if (this.currentSong?.album) {
  10213. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  10214. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  10215. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  10216. }
  10217. }
  10218. ToastUtil.showShort("保存成功")
  10219. this.isJumpSetting = false
  10220. })
  10221. }
  10222. .margin({
  10223. left: 38,
  10224. right: 38,
  10225. top: 10,
  10226. bottom: 10
  10227. })
  10228. .width(120)
  10229. .height(50)
  10230. }
  10231. }
  10232. }
  10233. .width('100%')
  10234. .height('100%')
  10235. }
  10236. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  10237. private onStateVastChange(state: AVCastPickerState) {
  10238. if (state == AVCastPickerState.STATE_APPEARING) {
  10239. console.log('The picker starts showing.');
  10240. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10241. console.log('The picker finishes presenting.');
  10242. }
  10243. }
  10244. private showSelectLyric() {
  10245. DialogHelper.showActionSheetDialog({
  10246. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  10247. // sheets: ["本地歌词", "搜索歌词"],
  10248. sheets: [
  10249. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  10250. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  10251. ],
  10252. maskColor: Color.Transparent,
  10253. backgroundColor: $r('app.color.bg_card'),
  10254. transition: AnimationHelper.transitionInDown(666),
  10255. onAction: (index) => {
  10256. switch (index) {
  10257. case 0:
  10258. this.callFilePickerSelectFileForLyric()
  10259. break;
  10260. case 1:
  10261. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10262. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10263. this.initLyric(lyricPath);
  10264. }
  10265. break;
  10266. }
  10267. }
  10268. })
  10269. }
  10270. // 拉起picker选择文件管理器
  10271. async callFilePickerSelectFileForLyric(): Promise<void> {
  10272. try {
  10273. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  10274. DocumentSelectOptions.maxSelectNumber = 1
  10275. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  10276. let documentPicker = new picker.DocumentViewPicker();
  10277. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  10278. Logger.info(TAG,
  10279. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  10280. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  10281. this.saveVideoDatasLyric(DocumentSelectResult)
  10282. }
  10283. }).catch((err: BusinessError) => {
  10284. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  10285. });
  10286. } catch (err) {
  10287. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  10288. }
  10289. }
  10290. async saveVideoDatasLyric(uris: string[]) {
  10291. if (ArrayUtil.isEmpty(uris)) {
  10292. return
  10293. }
  10294. let newUris: string[] = [];
  10295. for (let i = 0; i < uris.length; i++) {
  10296. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  10297. Logger.info(TAG, 'filePath uri: ' + filePath);
  10298. newUris.push(filePath)
  10299. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  10300. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  10301. fileIo.copyFileSync(file.fd, file2.fd)
  10302. fileIo.closeSync(file);
  10303. fileIo.closeSync(file2);
  10304. this.initLyric(filePath,false,false,true)
  10305. }
  10306. }
  10307. private initDelayPlay(context: object) {
  10308. this.mContext = context;
  10309. }
  10310. startPipLyric() {
  10311. if (this.pipController) {
  10312. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10313. PiPWindow.PiPControlStatus.PLAY);
  10314. }
  10315. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  10316. if (this.isOpenPip) {
  10317. this.startPip()
  10318. } else {
  10319. this.stopPip()
  10320. }
  10321. }
  10322. //startOffset 从cue分轨时间开始播
  10323. private startPlayOrResumePlay(startOffset?:number) {
  10324. //针对dsf文件高采样率sampleRate>441000,统一转wav播放
  10325. const sampleRate = this.currentSong?.sampleRate||0
  10326. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  10327. console.info('onecold 采样率 ='+sampleRate)
  10328. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  10329. console.info('onecold newDsfPath ='+newDsfPath)
  10330. if(!FileUtil.accessSync(newDsfPath)){
  10331. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  10332. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  10333. this.videoUrl = newDsfPath
  10334. this.startPlay(startOffset)
  10335. }).catch((e:object)=>{
  10336. console.info("task1 catch e: " + e);
  10337. })
  10338. }else{
  10339. this.videoUrl = newDsfPath
  10340. this.startPlay(startOffset)
  10341. }
  10342. }else{
  10343. this.startPlay(startOffset)
  10344. }
  10345. }
  10346. startPlay(startOffset?:number) {
  10347. this.startPipLyric()
  10348. this.mDestroyPage = false;
  10349. this.animationState = AnimationStatus.Running
  10350. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  10351. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10352. this.stopProgressTask();
  10353. this.startProgressTask();
  10354. this.play(this.videoUrl.toString(),startOffset);
  10355. }
  10356. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  10357. this.mIjkMediaPlayer.start();
  10358. this.setProgress()
  10359. this.CONTROL_PlayStatus = PlayStatus.PLAY
  10360. }
  10361. this.setIsPlaying(true)
  10362. this.updateSessionPlayState(true)
  10363. this.watchStatus();
  10364. this.updateLastPlayTimeStr(this.videoUrl)
  10365. }
  10366. updateLastPlayTimeStr(filePath: string) {
  10367. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  10368. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10369. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  10370. return;
  10371. }
  10372. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  10373. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  10374. if (success) {
  10375. this.getHistoryList(false)
  10376. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  10377. } else {
  10378. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  10379. }
  10380. });
  10381. }
  10382. private completionNum(num: number): string | number {
  10383. if (num < 10) {
  10384. return '0' + num;
  10385. } else {
  10386. return num;
  10387. }
  10388. }
  10389. private stringForTime(timeMs: number): string {
  10390. let totalSeconds: number | string = (timeMs / 1000);
  10391. let newSeconds: number | string = totalSeconds % 60;
  10392. let minutes: number | string = (totalSeconds / 60) % 60;
  10393. let hours: number | string = totalSeconds / 3600;
  10394. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  10395. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  10396. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  10397. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  10398. if (this.isCurrentTime) {
  10399. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  10400. this.oldSeconds = newSeconds
  10401. } else {
  10402. newSeconds = this.oldSeconds
  10403. }
  10404. }
  10405. newSeconds = this.completionNum(newSeconds);
  10406. if (hours > 0) {
  10407. return hours + ":" + minutes + ":" + newSeconds;
  10408. } else {
  10409. return minutes + ":" + newSeconds;
  10410. }
  10411. }
  10412. private setProgress() {
  10413. let position = this.mIjkMediaPlayer.getCurrentPosition();
  10414. let duration = this.mIjkMediaPlayer.getDuration();
  10415. let pos = 0;
  10416. if (duration > 0) {
  10417. this.slideEnable = true;
  10418. let curPercent = position / duration;
  10419. pos = curPercent * 100;
  10420. if (pos > this.PROGRESS_MAX_VALUE) {
  10421. this.progressValue = this.PROGRESS_MAX_VALUE
  10422. } else {
  10423. this.progressValue = pos;
  10424. }
  10425. }
  10426. // LogUtils.getInstance()
  10427. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10428. this.totalTime = this.stringForTime(duration);
  10429. if (position > duration) {
  10430. position = duration;
  10431. }
  10432. this.isCurrentTime = true;
  10433. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  10434. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  10435. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  10436. this.currentTime = this.stringForTime(position);
  10437. this.isCurrentTime = false
  10438. if (this.mIjkMediaPlayer.isPlaying()) {
  10439. this.randomColor =
  10440. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  10441. //如果是开启AB循环
  10442. if(this.isOpenAB){
  10443. if(position >=this.jumpBTime){
  10444. this.seekTo(this.jumpATime+'')
  10445. return
  10446. }
  10447. }
  10448. // 判断是否播放到结束时间
  10449. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  10450. if (position >= duration - this.jumpEndTime * 1000) {
  10451. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  10452. this.CONTROL_PlayStatus = PlayStatus.INIT
  10453. this.startPlayOrResumePlay();
  10454. }else if (this.playType == 2) { //2:正常播放,单曲播完
  10455. this.showRePlay();
  10456. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  10457. this.progressValue = this.PROGRESS_MAX_VALUE;
  10458. this.slideEnable = false;
  10459. this.stop();
  10460. // ToastUtil.showToast('开始重新播放')
  10461. }else{
  10462. this.playNext()
  10463. }
  10464. }
  10465. }
  10466. } else {
  10467. this.randomColor = 'rbg(0,0,0)'
  10468. }
  10469. }
  10470. private startProgressTask() {
  10471. let that = this;
  10472. this.updateProgressTimer = setInterval(() => {
  10473. //LogUtils.getInstance().LOGI("startProgressTask");
  10474. if (!that.mDestroyPage) {
  10475. that.setProgress();
  10476. }
  10477. }, 300);
  10478. }
  10479. private stopProgressTask() {
  10480. LogUtils.getInstance().LOGI("stopProgressTask");
  10481. clearInterval(this.updateProgressTimer);
  10482. }
  10483. private showLoadIng() {
  10484. this.loadingVisible = Visibility.Visible;
  10485. this.replayVisible = Visibility.None;
  10486. }
  10487. private hideLoadIng() {
  10488. this.loadingVisible = Visibility.None;
  10489. this.replayVisible = Visibility.None;
  10490. }
  10491. private showRePlay() {
  10492. this.loadingVisible = Visibility.None;
  10493. this.replayVisible = Visibility.Visible;
  10494. }
  10495. /**
  10496. * 为WebDAV请求添加认证头
  10497. */
  10498. private addWebDavAuthHeader(headers: Map<string, string>, accountId: number): void {
  10499. try {
  10500. // 从WebDAV管理器获取账户信息
  10501. const webdavManager = WebdavManager.getInstance();
  10502. const accounts = webdavManager.getAllWebDavAccounts();
  10503. const account = accounts.find(acc => acc.id === accountId);
  10504. if (account && account.account && account.password) {
  10505. // 构建Basic认证头
  10506. const credentials = `${account.account}:${account.password}`;
  10507. // 简单的Base64编码实现
  10508. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  10509. let encoded = '';
  10510. let i = 0;
  10511. while (i < credentials.length) {
  10512. const a = credentials.charCodeAt(i++);
  10513. const b = i < credentials.length ? credentials.charCodeAt(i++) : 0;
  10514. const c = i < credentials.length ? credentials.charCodeAt(i++) : 0;
  10515. const bitmap = (a << 16) | (b << 8) | c;
  10516. encoded += chars.charAt((bitmap >> 18) & 63);
  10517. encoded += chars.charAt((bitmap >> 12) & 63);
  10518. encoded += chars.charAt((bitmap >> 6) & 63);
  10519. encoded += chars.charAt(bitmap & 63);
  10520. }
  10521. // 处理剩余字符
  10522. const remainder = credentials.length % 3;
  10523. if (remainder === 1) {
  10524. const bitmap = credentials.charCodeAt(credentials.length - 1) << 16;
  10525. encoded += chars.charAt((bitmap >> 18) & 63);
  10526. encoded += chars.charAt((bitmap >> 12) & 63);
  10527. encoded += '==';
  10528. } else if (remainder === 2) {
  10529. const bitmap = (credentials.charCodeAt(credentials.length - 2) << 16) | (credentials.charCodeAt(credentials.length - 1) << 8);
  10530. encoded += chars.charAt((bitmap >> 18) & 63);
  10531. encoded += chars.charAt((bitmap >> 12) & 63);
  10532. encoded += chars.charAt((bitmap >> 6) & 63);
  10533. encoded += '=';
  10534. }
  10535. headers.set("Authorization", `Basic ${encoded}`);
  10536. Logger.info(`heanup 为WebDAV添加Basic认证头,账户: ${account.account}`);
  10537. } else {
  10538. Logger.warn(`heanup 未找到WebDAV账户信息或账户缺少认证信息,accountId: ${accountId}`);
  10539. }
  10540. } catch (error) {
  10541. Logger.error(`heanup 添加WebDAV认证头失败: ${error}`);
  10542. }
  10543. }
  10544. private async play(url: string,startOffset?:number) {
  10545. let that = this;
  10546. that.showLoadIng();
  10547. this.isOpenAB = false
  10548. //设置XComponent回调的context
  10549. if (!!this.mContext) {
  10550. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  10551. }
  10552. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10553. this.mIjkMediaPlayer.reset();
  10554. }
  10555. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  10556. //设置debug模式
  10557. this.mIjkMediaPlayer.setDebug(false);
  10558. //初始化配置
  10559. this.mIjkMediaPlayer.native_setup();
  10560. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  10561. if(this.volumeSmall){
  10562. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  10563. this.mIjkMediaPlayer.setVolume('1', '1');
  10564. }else{
  10565. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10566. }
  10567. }else{
  10568. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10569. }
  10570. //设置视频源
  10571. this.mIjkMediaPlayer.setDataSource(url);
  10572. //设置视频源http请求头
  10573. let headers = new Map([
  10574. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (ttmusic)"],
  10575. ["referer", "https://www.bilibili.com"]
  10576. ]);
  10577. // 如果是WebDAV网络音频,添加安全的HTTP头认证
  10578. Logger.info(`heanup 开始检查WebDAV认证需求 - currentSong存在: ${!!this.currentSong}`);
  10579. let isWebDavSong = false;
  10580. let webDavAuthInfo: WebDavAuthInfo | null = null;
  10581. if (this.currentSong) {
  10582. const currentSong = this.currentSong;
  10583. Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
  10584. // 检查是否为WebDAV歌曲(优先通过URL特征判断,因为全局上下文可能失效)
  10585. if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10586. isWebDavSong=true;
  10587. // 优先从实例变量获取认证信息(更可靠)
  10588. if (this.currentWebDavAuthInfo) {
  10589. webDavAuthInfo = this.currentWebDavAuthInfo;
  10590. Logger.info(`heanup 从实例变量获取到WebDAV认证信息,账户ID: ${webDavAuthInfo.accountId}`);
  10591. } else {
  10592. // 回退到全局上下文
  10593. try {
  10594. const globalContext = GlobalContext.getContext();
  10595. webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthInfo;
  10596. if (webDavAuthInfo) {
  10597. Logger.info(`heanup 从全局上下文获取到WebDAV认证信息,账户ID: ${webDavAuthInfo.accountId}`);
  10598. // 保存到实例变量中作为备份
  10599. this.currentWebDavAuthInfo = webDavAuthInfo;
  10600. } else {
  10601. Logger.warn(`heanup 全局上下文中没有WebDAV认证信息`);
  10602. }
  10603. } catch (error) {
  10604. Logger.error(`heanup 获取全局上下文失败:`, error.toString());
  10605. }
  10606. }
  10607. // 如果识别为WebDAV但没有认证信息,尝试使用默认配置或提示用户
  10608. if (!webDavAuthInfo) {
  10609. Logger.warn(`heanup 识别为WebDAV播放但缺少认证信息,可能需要手动配置WebDAV账户`);
  10610. // TODO: 可以在这里添加默认认证逻辑或用户提示
  10611. }
  10612. }
  10613. if (isWebDavSong&&webDavAuthInfo) {
  10614. // URL已在doPlay中编码过,这里无需再编码
  10615. // 但确保当前使用的this.videoUrl是已编码的版本
  10616. Logger.info(`heanup 检测到WebDAV播放,添加安全认证头`);
  10617. Logger.info(`heanup 歌曲URL: ${this.videoUrl}`);
  10618. try {
  10619. if (webDavAuthInfo && webDavAuthInfo.accountId) {
  10620. Logger.info(`heanup 找到WebDAV认证信息,账户ID: ${webDavAuthInfo.accountId}`);
  10621. // 使用WebdavManager获取认证头
  10622. const webdavManager = WebdavManager.getInstance();
  10623. const authHeaders = webdavManager.getWebDavAuthHeaders(webDavAuthInfo.accountId);
  10624. if (authHeaders) {
  10625. // 添加Basic认证头
  10626. headers.set("authorization", authHeaders.headers.Authorization);
  10627. } else {
  10628. Logger.error(`heanup 无法获取WebDAV认证头`);
  10629. }
  10630. } else {
  10631. Logger.error(`heanup WebDAV认证信息无效或缺少accountId`);
  10632. }
  10633. } catch (error) {
  10634. Logger.error(`heanup 获取WebDAV认证信息失败:`, error.toString());
  10635. }
  10636. // 添加标准的WebDAV请求头
  10637. headers.set("user_agent", "TTMusic-WebDAV/1.0");
  10638. headers.set("accept", "*/*");
  10639. headers.set("accept-range", "bytes");
  10640. Logger.info(`heanup WebDAV安全认证头设置完成`);
  10641. }
  10642. }
  10643. // 输出所有设置的头部信息用于调试
  10644. console.log(`heanup 设置的HTTP头部信息:`);
  10645. const headerIterator = headers.entries();
  10646. let headerEntry = headerIterator.next();
  10647. while (!headerEntry.done) {
  10648. const key = headerEntry.value[0];
  10649. const value = headerEntry.value[1];
  10650. console.log(`heanup ${key}: ${value}`);
  10651. // if (key.toLowerCase().includes('auth')) {
  10652. // Logger.info(`heanup ${key}: [认证信息已隐藏]`);
  10653. // } else {
  10654. // Logger.info(`heanup ${key}: ${value}`);
  10655. // }
  10656. headerEntry = headerIterator.next();
  10657. }
  10658. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  10659. if (isWebDavSong) {
  10660. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  10661. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  10662. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  10663. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  10664. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  10665. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  10666. // 缓冲和播放优化设置
  10667. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  10668. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  10669. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  10670. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  10671. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  10672. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  10673. // 网络相关设置
  10674. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  10675. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  10676. // 重连设置
  10677. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  10678. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  10679. }
  10680. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  10681. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  10682. // }
  10683. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10684. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  10685. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  10686. const fileSize = await this.getFileSize(this.videoUrl);
  10687. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  10688. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  10689. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  10690. }
  10691. // 使用软件解码(通常比硬件解码更节省内存)
  10692. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  10693. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  10694. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  10695. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  10696. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  10697. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  10698. //停止预读的最小帧数
  10699. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  10700. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  10701. // 设置其他缓冲相关选项
  10702. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  10703. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  10704. //启动预加载
  10705. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  10706. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  10707. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  10708. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  10709. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  10710. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  10711. // 因此需要播放器丢包,才不会累积延时
  10712. // 这个和第三个参数packet-buffering无关。
  10713. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  10714. // 无限制收流
  10715. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  10716. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  10717. // 屏幕常亮
  10718. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  10719. // 设置超时
  10720. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  10721. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  10722. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  10723. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  10724. // 变速播放
  10725. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  10726. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10727. let Speed = this.mIjkMediaPlayer.getSpeed()
  10728. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  10729. //是否开启循环播放
  10730. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  10731. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  10732. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  10733. if (height === 0) {
  10734. return;
  10735. }
  10736. const va = width / height;
  10737. const vpa = that.videoParentAspectRatio;
  10738. if (vpa > va) {
  10739. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  10740. } else {
  10741. that.videoWidth = '100%';
  10742. }
  10743. if (width && height) {
  10744. that.videoAspectRatio = width / height;
  10745. }
  10746. LogUtils.getInstance()
  10747. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  10748. that.hideLoadIng();
  10749. }
  10750. }
  10751. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  10752. let mOnPreparedListener: OnPreparedListener = {
  10753. onPrepared: async () => {
  10754. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  10755. try {
  10756. // this.cover = this.songList[this.curIndex].pixelMapPath
  10757. // this.artist = this.songList[this.curIndex].artist
  10758. // this.videoUrl = this.songList[this.curIndex].filePath
  10759. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10760. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  10761. this.setImageColor2(this.cover)
  10762. } else {
  10763. this.getImageColor();
  10764. }
  10765. //保存碰一碰分享的当前的歌曲
  10766. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  10767. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10768. await this.initLyric(lyricPath);
  10769. setTimeout(() => {
  10770. this.avSessionController.initAvSession(false);
  10771. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  10772. this.setAvSessionListener();
  10773. this.updateSessionPlayState(true)
  10774. this.setCurrentPlayMode()
  10775. }, 500)
  10776. if(startOffset&&startOffset>0){//cue分轨播放
  10777. this.seekTo(startOffset + "");
  10778. this.saveLastPlayList()
  10779. return
  10780. }
  10781. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10782. let timeoutPlay = 0
  10783. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10784. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  10785. timeoutPlay = 1000
  10786. }
  10787. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  10788. if (this.modeType === 0) { //文件夹
  10789. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10790. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  10791. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  10792. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  10793. } else if (this.modeType === 1) { //媒体库
  10794. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  10795. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  10796. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  10797. } else if (this.modeType === 2) { //艺术家
  10798. if (this.currentSong?.artist) {
  10799. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  10800. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  10801. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  10802. }
  10803. } else if (this.modeType === 3) { //专辑
  10804. if (this.currentSong?.album) {
  10805. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  10806. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  10807. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  10808. }
  10809. }
  10810. this.duration = this.mIjkMediaPlayer.getDuration()
  10811. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  10812. if (this.mIjkMediaPlayer != null) {
  10813. let jumpTopTimeMs = this.jumpTopTime*1000;
  10814. if (jumpTopTimeMs <= this.duration) {
  10815. // 调用 seekTo 方法,跳到指定时间
  10816. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  10817. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  10818. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10819. console.log('onecold position = '+position);
  10820. if (position > jumpTopTimeMs) {
  10821. jumpTopTimeMs = position
  10822. }
  10823. }
  10824. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10825. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10826. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  10827. }
  10828. }, timeoutPlay)
  10829. } else {
  10830. // 提示用户无法跳过
  10831. ToastUtil.showToast('跳过时间超过视频时长');
  10832. }
  10833. }
  10834. } else {
  10835. this.jumpTopTime = 0
  10836. this.jumpEndTime = 0
  10837. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  10838. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  10839. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  10840. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  10841. //记忆播放(每一首都会记忆播放)
  10842. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10843. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10844. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  10845. this.restorePlaybackPosition() //读取播放记忆功能
  10846. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  10847. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  10848. this.restorePlaybackPosition() //读取播放记忆功能
  10849. }
  10850. this.isFirstStartPlay = false
  10851. }, timeoutPlay)
  10852. } else {
  10853. this.isFirstStartPlay = false
  10854. }
  10855. }
  10856. this.saveLastPlayList()
  10857. } catch (error) {
  10858. let err: BusinessError = error as BusinessError;
  10859. console.error('onecold failed with err: ' + JSON.stringify(err));
  10860. }
  10861. }
  10862. }
  10863. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  10864. let mOnTimedTextListener: OnTimedTextListener = {
  10865. onTimedText: () => {
  10866. }
  10867. }
  10868. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  10869. let mOnCompletionListener: OnCompletionListener = {
  10870. onCompletion: () => {
  10871. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  10872. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  10873. this.playNext()
  10874. } else if (this.playType == 1) { //1:单片重复播放
  10875. this.CONTROL_PlayStatus = PlayStatus.INIT
  10876. console.info('onecold startPlayOrResumePlay 10592')
  10877. that.startPlayOrResumePlay();
  10878. } else if (this.playType == 2) { //2:正常播放,单曲播完
  10879. that.showRePlay();
  10880. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  10881. that.progressValue = this.PROGRESS_MAX_VALUE;
  10882. that.slideEnable = false;
  10883. that.stop();
  10884. // ToastUtil.showToast('开始重新播放')
  10885. } else if (this.playType == 3) { //3:随机播放
  10886. this.randomPlay()
  10887. }
  10888. }
  10889. }
  10890. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  10891. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  10892. onBufferingUpdate: (percent: number) => {
  10893. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  10894. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  10895. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  10896. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  10897. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  10898. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  10899. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  10900. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  10901. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  10902. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  10903. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  10904. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  10905. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  10906. let Looping = this.mIjkMediaPlayer.isLooping()
  10907. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  10908. }
  10909. }
  10910. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  10911. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  10912. onSeekComplete: () => {
  10913. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  10914. console.info('onecold startPlayOrResumePlay 10643')
  10915. that.startPlayOrResumePlay();
  10916. }
  10917. }
  10918. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  10919. let mOnInfoListener: OnInfoListener = {
  10920. onInfo: (what: number, extra: number) => {
  10921. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  10922. that.hideLoadIng();
  10923. }
  10924. }
  10925. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  10926. let mOnErrorListener: OnErrorListener = {
  10927. onError: (what: number, extra: number) => {
  10928. this.stopProgressTask();
  10929. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  10930. // 检查是否为WebDAV播放错误
  10931. let isWebDavError = false;
  10932. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV && this.currentSong.filePath) {
  10933. try {
  10934. const globalContext = GlobalContext.getContext();
  10935. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthInfo;
  10936. if (webDavAuthInfo) {
  10937. isWebDavError = true;
  10938. } else {
  10939. // 通过URL特征判断
  10940. const filePath = this.currentSong.filePath;
  10941. if (filePath.includes('/webdav') || filePath.includes(':5005') || filePath.includes(':5000') ||
  10942. filePath.includes('/remote.php') || filePath.includes('/dav/')) {
  10943. isWebDavError = true;
  10944. }
  10945. }
  10946. } catch (error) {
  10947. // 通过URL特征判断
  10948. const filePath = this.currentSong.filePath;
  10949. if (filePath.includes('/webdav') || filePath.includes(':8080') || filePath.includes(':5000') ||
  10950. filePath.includes('/remote.php') || filePath.includes('/dav/')) {
  10951. isWebDavError = true;
  10952. }
  10953. }
  10954. }
  10955. if (isWebDavError) {
  10956. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  10957. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  10958. // this.currentWebDavAuthInfo = null;
  10959. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  10960. // 根据错误代码提供更具体的错误信息
  10961. let errorMessage = "WebDAV播放失败";
  10962. if (what === -1) { // 网络错误
  10963. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  10964. } else if (what === -1004) { // HTTP 404
  10965. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  10966. } else if (what === -1001) { // 超时
  10967. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  10968. } else if (what === -1003) { // 无法解析主机
  10969. errorMessage = "无法连接到WebDAV服务器";
  10970. }
  10971. ToastUtil.showToast(errorMessage);
  10972. } else {
  10973. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10974. !this.videoUrl.startsWith('http://') &&
  10975. !this.videoUrl.startsWith('https://') &&
  10976. !FileUtil.accessSync(this.videoUrl)) {
  10977. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  10978. } else {
  10979. ToastUtil.showToast(getContext()
  10980. .resourceManager
  10981. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  10982. }
  10983. }
  10984. that.hideLoadIng();
  10985. }
  10986. }
  10987. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  10988. this.mIjkMediaPlayer.setMessageListener();
  10989. this.mIjkMediaPlayer.prepareAsync();
  10990. this.mIjkMediaPlayer.start();
  10991. }
  10992. //保存最后播放的那首歌和已经对应的播放列表
  10993. saveLastPlayList() {
  10994. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  10995. PreferencesUtil.putSync('LastMusicList', this.songList)
  10996. }
  10997. // 清空播放记录
  10998. clearVideoHistory() {
  10999. this.table.clearPlayHistory((success: boolean, error?: string) => {
  11000. if (success) {
  11001. this.historyList = [];
  11002. this.updateListData(this.historyList)
  11003. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  11004. ToastUtil.showToast('清空播放记录成功')
  11005. } else {
  11006. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  11007. }
  11008. });
  11009. }
  11010. public async setAvSessionListener() {
  11011. if (!this.avSessionController) {
  11012. return;
  11013. }
  11014. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  11015. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  11016. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  11017. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  11018. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  11019. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  11020. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  11021. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  11022. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  11023. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  11024. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  11025. }
  11026. setLoopMode() {
  11027. let itype = this.playType + 1
  11028. if (itype >= 4) {
  11029. this.playType = 0
  11030. ToastUtil.showToast('连续播放')
  11031. } else if (itype === 1) {
  11032. this.playType = 1
  11033. ToastUtil.showToast('单曲循环')
  11034. } else if (itype === 2) {
  11035. this.playType = 2
  11036. ToastUtil.showToast('单曲播完')
  11037. } else if (itype === 3) {
  11038. this.playType = 3
  11039. ToastUtil.showToast('随机播放')
  11040. } else if (itype === 0) {
  11041. this.playType = 0
  11042. ToastUtil.showToast('连续播放')
  11043. }
  11044. PreferencesUtil.putSync('musicPlayType', this.playType)
  11045. this.setCurrentPlayMode()
  11046. }
  11047. private sessionSetLoopModeCallback = (mode: number) => {
  11048. if (this.mIjkMediaPlayer != null) {
  11049. ToastUtil.showToast('当前播放模式:' + mode)
  11050. Logger.info('onecold 当前播放模式= ' + mode)
  11051. let hmPlayMode = mode + 1
  11052. if (hmPlayMode >= 4) {
  11053. hmPlayMode = 0
  11054. }
  11055. if (hmPlayMode === 1) {
  11056. this.playType = 1
  11057. ToastUtil.showToast('单曲循环')
  11058. } else if (hmPlayMode === 0) {
  11059. this.playType = 2
  11060. ToastUtil.showToast('单曲播完')
  11061. } else if (hmPlayMode === 3) {
  11062. this.playType = 3
  11063. ToastUtil.showToast('随机播放')
  11064. } else if (hmPlayMode === 2) {
  11065. this.playType = 0
  11066. ToastUtil.showToast('连续播放')
  11067. }
  11068. PreferencesUtil.putSync('musicPlayType', this.playType)
  11069. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  11070. let playBackState: avSession.AVPlaybackState = {
  11071. loopMode: hmPlayMode,
  11072. };
  11073. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  11074. console.info(`set setLoopMode AVPlaybackState successfully`);
  11075. }).catch((err: BusinessError) => {
  11076. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11077. });
  11078. }
  11079. }
  11080. setCurrentPlayMode() {
  11081. if (!this.avSessionController) {
  11082. return;
  11083. }
  11084. let mLoopMode = 0
  11085. switch (this.playType) {
  11086. case 0:
  11087. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  11088. break;
  11089. case 1:
  11090. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  11091. break;
  11092. case 2:
  11093. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  11094. break;
  11095. case 3:
  11096. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  11097. break;
  11098. }
  11099. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  11100. let playBState: avSession.AVPlaybackState = {
  11101. loopMode: mLoopMode,
  11102. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  11103. };
  11104. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  11105. console.info(`set setLoopMode AVPlaybackState successfully`);
  11106. }).catch((err: BusinessError) => {
  11107. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11108. });
  11109. }
  11110. private sessionToggleFavoriteCallback = (assetId: string) => {
  11111. if (this.mIjkMediaPlayer != null && this.currentSong) {
  11112. console.info(`on toggleFavorite `);
  11113. // 应用收到收藏命令,进行收藏处理。
  11114. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  11115. this.doFav(this.currentSong)
  11116. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  11117. let playbackState: avSession.AVPlaybackState = {
  11118. isFavorite: !this.isFac,
  11119. };
  11120. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  11121. console.info(`SetAVPlaybackState successfully`);
  11122. }).catch((err: BusinessError) => {
  11123. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  11124. });
  11125. }
  11126. }
  11127. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  11128. device: avSession.OutputDeviceInfo) => {
  11129. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  11130. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11131. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  11132. await this.startCasting();
  11133. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11134. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  11135. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  11136. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  11137. if (device) {
  11138. this.endCasting();
  11139. }
  11140. }
  11141. };
  11142. private async startCasting() {
  11143. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11144. this.setPlaybackStateChangeListener();
  11145. this.pause();
  11146. this.initQueueItem();
  11147. this.prepare();
  11148. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11149. refToIsCasting?.set(true);
  11150. this.castSeek = true;
  11151. this.isCastPlaying = true;
  11152. }
  11153. async changeCasting() {
  11154. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11155. this.initQueueItem();
  11156. this.prepare();
  11157. this.setPlaybackStateChangeListener();
  11158. this.isCastPlaying = true;
  11159. this.castSeek = true;
  11160. }
  11161. public endCasting() {
  11162. this.avSessionController.getAvSession()?.stopCasting();
  11163. this.stopCast();
  11164. this.isCastPlaying = false;
  11165. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11166. refToIsCasting?.set(false);
  11167. this.pause();
  11168. this.setIsPlaying(false);
  11169. // if (this.curIndex === this.curSource.index) {
  11170. // this.play
  11171. // this.seek(this.currentTime * 1000);
  11172. // this.setIsPlaying(true);
  11173. // } else {
  11174. // this.pauseVideo();
  11175. // this.setIsPlaying(false);
  11176. // }
  11177. }
  11178. public setIsPlaying(isPlayer: boolean) {
  11179. this.isPlaying = isPlayer;
  11180. // 发送播放状态变化事件给歌单详情页面
  11181. try {
  11182. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  11183. const currentFilePath = this.currentSong?.filePath || ''
  11184. const eventData: emitter.EventData = {
  11185. data: {
  11186. isPlaying: this.isPlaying,
  11187. curIndex: this.curIndex,
  11188. currentFilePath: currentFilePath
  11189. }
  11190. };
  11191. emitter.emit(eventPlaybackStatus, eventData)
  11192. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  11193. } catch (error) {
  11194. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  11195. }
  11196. }
  11197. private setPlaybackStateChangeListener(): void {
  11198. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  11199. this.castController?.on('endOfStream', this.reloadCasting);
  11200. this.castController?.on('playNext', this.playNextCallback);
  11201. this.castController?.on('playPrevious', this.playPreviousCallback);
  11202. }
  11203. private updateSessionPlayState(isPlay: boolean): void {
  11204. // if(!this.isBgPlayOpen)
  11205. // return
  11206. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  11207. this.setAVSessionPlayState({
  11208. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  11209. position: {
  11210. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  11211. updateTime: new Date().getTime()
  11212. }
  11213. });
  11214. }
  11215. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  11216. this.avSessionController.setAvSessionPlayState(playbackState)
  11217. }
  11218. private positionChange(position: number) {
  11219. this.currentTime2 = position / 1000;
  11220. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  11221. }
  11222. private playDurationChange(duration: number) {
  11223. this.duration = duration;
  11224. this.durationTime = Math.floor(this.duration / 1000);
  11225. this.durationStringTime = secondToTime((this.durationTime));
  11226. }
  11227. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  11228. const duration = playbackState?.extras?.duration;
  11229. if (typeof duration === 'number') {
  11230. this.playDurationChange(duration as number);
  11231. }
  11232. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  11233. this.positionChange(playbackState?.position?.elapsedTime);
  11234. }
  11235. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  11236. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  11237. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  11238. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  11239. this.isCastPlaying = false;
  11240. }
  11241. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  11242. this.isCastPlaying = true;
  11243. }
  11244. };
  11245. private reloadCasting = async () => {
  11246. let item = this.songList[this.curIndex];
  11247. let uri = fileUri.getUriFromPath(item.filePath);
  11248. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11249. // description.startPosition = 0;
  11250. this.castItem = {
  11251. itemId: this.curIndex,
  11252. description: {
  11253. assetId: item.filePath,
  11254. title: item.name,
  11255. artist: '',
  11256. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11257. // mediaUri: item.filePath,
  11258. fdSrc: {
  11259. fd: file.fd
  11260. },
  11261. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11262. mediaType: 'VIDEO',
  11263. mediaSize: item.videoSize,
  11264. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11265. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11266. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11267. duration: this.duration,
  11268. // albumCoverUri: 'https://www.example.jpeg',
  11269. // albumTitle: '《ExampleAlbum》',
  11270. appName: this.appName,
  11271. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11272. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11273. }
  11274. };
  11275. this.prepare();
  11276. this.isCastPlaying = true;
  11277. };
  11278. public playNextCallback = (): void => {
  11279. this.playNext()
  11280. };
  11281. public playPreviousCallback = (): void => {
  11282. this.playPrevious()
  11283. };
  11284. async prepare() {
  11285. await this.castController?.prepare(this.castItem);
  11286. await this.castController?.start(this.castItem);
  11287. }
  11288. public initQueueItem() {
  11289. let item = this.songList[this.curIndex];
  11290. let time = this.currentTime;
  11291. let uri = fileUri.getUriFromPath(item.filePath);
  11292. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11293. this.castItem = {
  11294. itemId: this.curIndex,
  11295. description: {
  11296. assetId: item.filePath,
  11297. title: item.name,
  11298. artist: '',
  11299. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11300. fdSrc: {
  11301. fd: file.fd
  11302. },
  11303. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11304. mediaType: 'AUDIO',
  11305. mediaSize: item.videoSize,
  11306. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11307. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11308. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11309. duration: this.duration,
  11310. // albumCoverUri: 'https://www.example.jpeg',
  11311. // albumTitle: '《ExampleAlbum》',
  11312. appName: this.appName,
  11313. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11314. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11315. }
  11316. };
  11317. }
  11318. async stopCast() {
  11319. try {
  11320. this.castController?.off('playbackStateChange');
  11321. this.castController?.off('endOfStream');
  11322. this.castController?.off('playNext');
  11323. this.castController?.off('playPrevious');
  11324. this.castController?.off('error');
  11325. } catch (error) {
  11326. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  11327. }
  11328. }
  11329. private sessionPlayCallback = (): void => {
  11330. console.info('onecold playOrPause 11050')
  11331. this.playOrPause()
  11332. };
  11333. private sessionPauseCallback = (): void => {
  11334. console.info('onecold playOrPause 11054')
  11335. this.pause()
  11336. };
  11337. private playOrPause() {
  11338. if (!this.debounce()) {
  11339. return;
  11340. }
  11341. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11342. this.pause();
  11343. } else {
  11344. console.info('onecold startPlayOrResumePlay 11064')
  11345. this.startPlayOrResumePlay();
  11346. this.playChange()
  11347. }
  11348. }
  11349. private sessionPlayNextCallback = (): void => {
  11350. this.playNext()
  11351. };
  11352. private sessionPlayPreviousCallback = (): void => {
  11353. this.playPrevious()
  11354. };
  11355. private sessionStopCallback = (): void => {
  11356. this.stop()
  11357. };
  11358. private sessionFastForwardCallback = (time?: number) => {
  11359. if (!time) {
  11360. return;
  11361. }
  11362. if (this.mIjkMediaPlayer != null) {
  11363. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11364. let seeTime = curPosition + time * 1000;
  11365. // 限制 seekValue 在合法范围内
  11366. if (seeTime < 0) {
  11367. seeTime = 0;
  11368. } else if (seeTime > this.duration) {
  11369. seeTime = this.duration;
  11370. }
  11371. Logger.info('onecold seeTime= ' + seeTime)
  11372. this.setSeekToActionProgress(seeTime)
  11373. this.seekTo(seeTime + "")
  11374. }
  11375. };
  11376. /**
  11377. * Gesture method onActionUpdate.
  11378. *
  11379. * @param event Gesture event.手势拖动设置快进和后退
  11380. */
  11381. private setSeekToActionProgress(position: number) {
  11382. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  11383. let duration = this.mIjkMediaPlayer.getDuration();
  11384. let pos = 0;
  11385. if (duration > 0) {
  11386. this.slideEnable = true;
  11387. let curPercent = position / duration;
  11388. pos = curPercent * 100;
  11389. if (pos > this.PROGRESS_MAX_VALUE) {
  11390. this.progressValue = this.PROGRESS_MAX_VALUE
  11391. } else {
  11392. this.progressValue = pos;
  11393. }
  11394. }
  11395. // LogUtils.getInstance()
  11396. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11397. this.totalTime = this.stringForTime(duration);
  11398. if (position > duration) {
  11399. position = duration;
  11400. }
  11401. this.isCurrentTime = true;
  11402. this.currentTime = this.stringForTime(position);
  11403. this.isCurrentTime = false
  11404. }
  11405. private sessionRewindCallback = (time?: number) => {
  11406. if (!time) {
  11407. return;
  11408. }
  11409. if (this.mIjkMediaPlayer != null) {
  11410. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11411. let seeTime = curPosition - time * 1000;
  11412. // 限制 seekValue 在合法范围内
  11413. if (seeTime < 0) {
  11414. seeTime = 0;
  11415. } else if (seeTime > this.duration) {
  11416. seeTime = this.duration;
  11417. }
  11418. Logger.info('onecold seeTime= ' + seeTime)
  11419. this.setSeekToActionProgress(seeTime)
  11420. this.seekTo(seeTime + "")
  11421. }
  11422. };
  11423. private sessionSeekCallback = (seekTime: number) => {
  11424. if (this.mIjkMediaPlayer != null) {
  11425. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11426. this.seekTo(seekTime + "")
  11427. }
  11428. };
  11429. private async getFileSize(filePath: string): Promise<number> {
  11430. try {
  11431. const stat = await fs.stat(filePath);
  11432. return stat.size;
  11433. } catch (err) {
  11434. console.error('Failed to get file size: ' + err.message);
  11435. return 0;
  11436. }
  11437. }
  11438. private pause() {
  11439. if (this.mIjkMediaPlayer.isPlaying()) {
  11440. this.savePlaybackPosition();
  11441. this.mIjkMediaPlayer.pause();
  11442. this.setProgress();
  11443. this.mDestroyPage = true;
  11444. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  11445. this.updateSessionPlayState(false)
  11446. this.playChange()
  11447. if (this.pipController) {
  11448. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11449. PiPWindow.PiPControlStatus.PAUSE);
  11450. }
  11451. }
  11452. }
  11453. private stop() {
  11454. this.savePlaybackPosition();
  11455. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11456. this.mIjkMediaPlayer.stop();
  11457. this.mIjkMediaPlayer.release();
  11458. this.stopProgressTask();
  11459. this.updateSessionPlayState(false)
  11460. this.playChange()
  11461. this.watchStatus();
  11462. }
  11463. //保持记忆播放功能
  11464. private savePlaybackPosition() {
  11465. if (this.mIjkMediaPlayer != null) {
  11466. const position = this.mIjkMediaPlayer.getCurrentPosition();
  11467. // ToastUtil.showToast('保存记忆播放 = ' + position)
  11468. const duration = this.mIjkMediaPlayer.getDuration();
  11469. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  11470. // 如果播放位置接近视频末尾,则保存 position 为 0
  11471. const playbackPosition = (duration - position < threshold) ? 0 : position;
  11472. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  11473. }
  11474. }
  11475. //获取记忆播放功能
  11476. private restorePlaybackPosition() {
  11477. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11478. // ToastUtil.showToast('position = ' + position)
  11479. if (this.mIjkMediaPlayer != null && position > 0) {
  11480. // ToastUtil.showToast('seekTo = ' + position)
  11481. this.seekTo(position + "");
  11482. }
  11483. }
  11484. private seekTo(value: string) {
  11485. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  11486. ToastUtil.showToast('wma格式不支持拖动快进。')
  11487. return
  11488. }
  11489. this.isSeekTo = true
  11490. this.mIjkMediaPlayer.seekTo(value);
  11491. console.info('onecold startPlayOrResumePlay 11227')
  11492. // this.startPlayOrResumePlay()
  11493. // 在这里恢复计时器状态
  11494. this.setProgress()
  11495. this.isSeekTo = false
  11496. }
  11497. // 添加到下一首播放
  11498. private addToNextPlay(song: VideoItem) {
  11499. if (!this.debounce()) {
  11500. return;
  11501. }
  11502. if (this.currentSong) {
  11503. if (this.currentSong === song) {
  11504. ToastUtil.showToast('当前已经在播放这首歌了!')
  11505. return
  11506. }
  11507. }
  11508. // 如果未开始播放或队列为空
  11509. if (this.curIndex === -1 || this.songList.length === 0) {
  11510. this.songList = [song];
  11511. this.curIndex = 0;
  11512. this.doPlay(song)
  11513. return;
  11514. }
  11515. // 插入到当前索引+1的位置
  11516. const insertPos = this.curIndex + 1;
  11517. this.songList.splice(insertPos, 0, song);
  11518. this.songList = [...this.songList]; // 触发状态更新
  11519. this.sonDataSource.pushArrayData(this.songList)
  11520. ToastUtil.showToast('已添加至下一首播放')
  11521. }
  11522. //后退10s,可再设置设置默认几秒
  11523. backForward() {
  11524. if(this.mIjkMediaPlayer){
  11525. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11526. let value = pos - Number(this.fastForwardSeconds) * 1000;
  11527. this.seekTo(value+"");
  11528. }
  11529. }
  11530. //快进10s,可再设置设置默认几秒
  11531. fastForward() {
  11532. if(this.mIjkMediaPlayer){
  11533. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11534. let value = pos + Number(this.fastForwardSeconds) * 1000;
  11535. this.seekTo(value+"");
  11536. }
  11537. }
  11538. //下一个
  11539. private playNext() {
  11540. if (!this.debounce()) {
  11541. return;
  11542. }
  11543. if (this.playType == 3) { //3:随机播放
  11544. this.randomPlay()
  11545. return;
  11546. }
  11547. if (ArrayUtil.isNotEmpty(this.songList)) {
  11548. if (this.curIndex == this.songList.length - 1) {
  11549. this.curIndex = 0;
  11550. } else {
  11551. this.curIndex++;
  11552. }
  11553. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11554. this.stop();
  11555. this.currentSong = this.songList[this.curIndex]
  11556. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11557. this.artist = this.songList[this.curIndex].artist
  11558. this.name = this.songList[this.curIndex].name
  11559. //this.cover = this.songList[this.curIndex].pixelMapPath
  11560. this.changeImageAnimation()
  11561. }
  11562. }
  11563. changeImageAnimation() {
  11564. if(this.openSkipSongAnimate){
  11565. // 第一步:淡出动画
  11566. this.getUIContext()?.animateTo({
  11567. duration: 500,
  11568. curve: Curve.EaseOut,
  11569. }, () => {
  11570. this.opacityValueImage = 0.1;
  11571. if(this.isCoverRectangle){
  11572. this.scaleValueImage = 0.88
  11573. }
  11574. });
  11575. // 第二步:切换图片后淡入
  11576. setTimeout(() => {
  11577. this.cover = this.songList[this.curIndex].pixelMapPath
  11578. this.getUIContext()?.animateTo({
  11579. duration: 500,
  11580. curve: Curve.EaseIn,
  11581. }, () => {
  11582. this.opacityValueImage = 1;
  11583. this.scaleValueImage = 1 // 图标恢复到原始大小
  11584. this.startPlayOrResumePlay()
  11585. });
  11586. }, 500);
  11587. }else{
  11588. this.cover = this.songList[this.curIndex].pixelMapPath
  11589. this.startPlayOrResumePlay()
  11590. }
  11591. }
  11592. // 存储已播放的歌曲索引
  11593. private playedIndices: Set<number> = new Set();
  11594. //随机播放
  11595. private randomPlay() {
  11596. // if (!this.debounce()) {
  11597. // return;
  11598. // }
  11599. if (ArrayUtil.isNotEmpty(this.songList)) {
  11600. if (this.songList.length > 3) {
  11601. // 如果所有歌曲都播放过一次,清空已播放索引集合
  11602. if (this.playedIndices.size === this.songList.length) {
  11603. this.playedIndices.clear();
  11604. }
  11605. // 随机选择一个未播放的歌曲索引
  11606. let newIndex: number;
  11607. // 添加超时机制防止无限循环
  11608. let attempt = 0;
  11609. const maxAttempts = 100; // 根据需求调整
  11610. do {
  11611. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  11612. attempt++;
  11613. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  11614. if (attempt >= maxAttempts) {
  11615. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  11616. newIndex = Math.floor(Math.random() * this.songList.length);
  11617. }
  11618. this.curIndex = newIndex;
  11619. this.playedIndices.add(newIndex);
  11620. } else {
  11621. // 当歌曲数量小于或等于3时,直接播放下一首
  11622. if (this.curIndex == this.songList.length - 1) {
  11623. this.curIndex = 0;
  11624. } else {
  11625. this.curIndex++;
  11626. }
  11627. }
  11628. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11629. this.stop();
  11630. this.currentSong = this.songList[this.curIndex];
  11631. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11632. this.name = this.songList[this.curIndex].name;
  11633. this.artist = this.songList[this.curIndex].artist
  11634. // this.cover = this.songList[this.curIndex].pixelMapPath
  11635. this.changeImageAnimation()
  11636. }
  11637. }
  11638. private playIndex(index: number) {
  11639. if (!this.debounce()) {
  11640. return;
  11641. }
  11642. if (ArrayUtil.isNotEmpty(this.songList)) {
  11643. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11644. this.stop();
  11645. this.currentSong = this.songList[this.curIndex]
  11646. this.videoUrl = this.songList[index].filePath.replace(/ /g, '%20');
  11647. this.name = this.songList[index].name
  11648. this.artist = this.songList[this.curIndex].artist
  11649. this.curIndex = index;
  11650. this.changeImageAnimation()
  11651. }
  11652. }
  11653. //上一个
  11654. private playPrevious() {
  11655. if (!this.debounce()) {
  11656. return;
  11657. }
  11658. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  11659. this.randomModePlayFromHistory()
  11660. return;
  11661. }
  11662. if (this.curIndex == 0) {
  11663. this.curIndex = this.songList.length - 1;
  11664. } else {
  11665. this.curIndex--;
  11666. }
  11667. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11668. this.stop();
  11669. this.currentSong = this.songList[this.curIndex]
  11670. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11671. this.name = this.songList[this.curIndex].name
  11672. this.artist = this.songList[this.curIndex].artist
  11673. this.changeImageAnimation()
  11674. }
  11675. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  11676. private randomModePlayFromHistory() {
  11677. if (this.historyList.length >= 2) {
  11678. // 播放历史记录的第二首
  11679. const prevSong = this.historyList[1];
  11680. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  11681. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11682. this.stop();
  11683. this.currentSong = prevSong;
  11684. this.videoUrl = prevSong.filePath.replace(/ /g, '%20');
  11685. this.cover = prevSong.pixelMapPath
  11686. this.artist = prevSong.artist
  11687. this.name = prevSong.name;
  11688. console.info('onecold startPlayOrResumePlay 11434')
  11689. this.startPlayOrResumePlay();
  11690. } else {
  11691. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  11692. if (this.curIndex === 0) {
  11693. this.curIndex = this.songList.length - 1;
  11694. } else {
  11695. this.curIndex--;
  11696. }
  11697. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11698. this.stop();
  11699. this.currentSong = this.songList[this.curIndex];
  11700. this.videoUrl = this.songList[this.curIndex].filePath.replace(/ /g, '%20');
  11701. this.artist = this.songList[this.curIndex].artist
  11702. this.name = this.songList[this.curIndex].name;
  11703. this.changeImageAnimation()
  11704. }
  11705. }
  11706. debounce() {
  11707. const delay = 600;
  11708. let cur = new Date().getTime();
  11709. if (cur - this.last > delay) {
  11710. this.last = cur;
  11711. return true;
  11712. }
  11713. return false;
  11714. }
  11715. /**
  11716. * Sets whether the screen is a constant based on the playback status.
  11717. */
  11718. watchStatus() {
  11719. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  11720. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11721. this.windowClass.setWindowKeepScreenOn(true);
  11722. } else {
  11723. this.windowClass.setWindowKeepScreenOn(false);
  11724. }
  11725. }
  11726. /**
  11727. * Volume gesture method onActionStart.
  11728. *
  11729. * @param event Gesture event.
  11730. */
  11731. private customDialogComponentIdMM: number = 0
  11732. @Builder
  11733. customDialogComponentMM() {
  11734. Column() {
  11735. Row() {
  11736. Blank()
  11737. Text('验证密码')
  11738. .fontSize(22)
  11739. .fontColor($r('app.color.pri_bg'))
  11740. .margin({ top: 18 })
  11741. Blank()
  11742. Image($r('app.media.close'))
  11743. .fillColor(Color.White)
  11744. .margin({ top: 18, right: 18 })
  11745. .width(20)
  11746. .onClick(() => {
  11747. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11748. })
  11749. }
  11750. .width('100%') // 使Row占据整个宽度
  11751. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  11752. Verify({
  11753. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  11754. });
  11755. }.height('60%')
  11756. .backgroundColor($r('app.color.index_background'))
  11757. .justifyContent(FlexAlign.SpaceBetween)
  11758. }
  11759. private handleVerifyCompleted(isSuccess: boolean) {
  11760. if (isSuccess) {
  11761. console.log('验证成功');
  11762. // 在这里处理验证成功后的逻辑
  11763. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11764. this.currentPath = this.lockPath
  11765. this.getSortedFiles(this.currentPath)
  11766. } else {
  11767. // console.log('验证失败');
  11768. ToastUtil.showToast('验证失败')
  11769. }
  11770. }
  11771. private showVerifyDialog() {
  11772. promptAction.openCustomDialog({
  11773. transition: TransitionEffect.asymmetric(
  11774. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  11775. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11776. ,
  11777. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  11778. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11779. ),
  11780. builder: () => {
  11781. this.customDialogComponentMM()
  11782. },
  11783. isModal: true,
  11784. autoCancel: true,
  11785. maskColor: Color.Transparent,
  11786. alignment: DialogAlignment.Bottom,
  11787. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  11788. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  11789. console.log("dialog onWillDismiss")
  11790. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  11791. dismissDialogAction.dismiss()
  11792. }
  11793. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  11794. dismissDialogAction.dismiss()
  11795. }
  11796. }
  11797. }).then((dialogId: number) => {
  11798. this.customDialogComponentIdMM = dialogId
  11799. })
  11800. }
  11801. //左滑操作 移动文件 重命名 删除等操作
  11802. @Builder
  11803. DeleteButton(item: VideoItem, index: number, filePath: string) {
  11804. Row() {
  11805. //加入收藏
  11806. Button() {
  11807. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  11808. .fillColor(Color.White)
  11809. .width(20)
  11810. }
  11811. .width(40)
  11812. .height(40)
  11813. .type(ButtonType.Circle)
  11814. .backgroundColor(this.themeColor)
  11815. .margin(5)
  11816. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11817. .onClick(() => {
  11818. if (item) {
  11819. this.doFav(item)
  11820. }
  11821. })
  11822. //加入下一首播放
  11823. Button() {
  11824. Image($r('app.media.next_to_play'))
  11825. .fillColor(Color.White)
  11826. .width(20)
  11827. }
  11828. .width(40)
  11829. .height(40)
  11830. .type(ButtonType.Circle)
  11831. .backgroundColor(this.themeColor)
  11832. .margin(5)
  11833. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11834. .onClick(() => {
  11835. this.addToNextPlay(item);
  11836. })
  11837. //复制文件
  11838. Button() {
  11839. Image($r('app.media.copy'))
  11840. .fillColor(Color.White)
  11841. .width(20)
  11842. }
  11843. .width(40)
  11844. .height(40)
  11845. .type(ButtonType.Circle)
  11846. .backgroundColor(this.themeColor)
  11847. .margin(5)
  11848. .id(filePath + 'copy')
  11849. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11850. .onClick(() => {
  11851. this.showCopyDialog(false, item, index, filePath + 'copy');
  11852. })
  11853. //移动文件
  11854. Button() {
  11855. Image($r('app.media.cut'))
  11856. .fillColor(Color.White)
  11857. .width(20)
  11858. }
  11859. .width(40)
  11860. .height(40)
  11861. .type(ButtonType.Circle)
  11862. .backgroundColor(this.themeColor)
  11863. .margin(5)
  11864. .id(filePath)
  11865. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11866. .onClick(() => {
  11867. this.showCutDialog(false, item, index, filePath);
  11868. })
  11869. Button() {
  11870. Image($r('app.media.cut_current'))
  11871. .fillColor(Color.White)
  11872. .width(20)
  11873. }
  11874. .width(40)
  11875. .height(40)
  11876. .type(ButtonType.Circle)
  11877. .backgroundColor(this.themeColor)
  11878. .margin(5)
  11879. .id(filePath + 'current')
  11880. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  11881. (this.isHasDir ? Visibility.Visible : Visibility.None))
  11882. .onClick(() => {
  11883. this.showCutDialog(true, item, index, filePath + 'current');
  11884. })
  11885. //重命名
  11886. Button() {
  11887. Image($r('app.media.rename2'))
  11888. .fillColor(Color.White)
  11889. .width(20)
  11890. }
  11891. .width(40)
  11892. .height(40)
  11893. .type(ButtonType.Circle)
  11894. .backgroundColor(this.themeColor)
  11895. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11896. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11897. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11898. .margin(5)
  11899. .onClick(() => {
  11900. this.showReNameDialog(item, index + '', filePath)
  11901. })
  11902. Button() {
  11903. Image($r('app.media.delete2'))
  11904. .fillColor(Color.White)
  11905. .width(20)
  11906. }
  11907. .width(40)
  11908. .height(40)
  11909. .type(ButtonType.Circle)
  11910. .backgroundColor(this.themeColor)
  11911. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11912. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11913. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11914. .margin(5)
  11915. .onClick(() => {
  11916. this.selectedFiles.push(item)
  11917. this.showWarnIsDelete()
  11918. // this.showWarnIsDeleteFile(item, index + '', filePath)
  11919. })
  11920. Button() {
  11921. Image($r('app.media.share2'))
  11922. .fillColor(Color.White)
  11923. .width(20)
  11924. }
  11925. .width(40)
  11926. .height(40)
  11927. .type(ButtonType.Circle)
  11928. .backgroundColor(this.themeColor)
  11929. .margin(5)
  11930. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11931. .onClick(() => {
  11932. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11933. })
  11934. }
  11935. }
  11936. /**
  11937. * 穿山甲banner广告
  11938. */
  11939. // private declare bannerAd: CSJNativeExpressAd;
  11940. // @State private status: string = "未加载"
  11941. // @State private isShowAd: boolean = false
  11942. // private declare mAdSlot: AdSlot;
  11943. // private mBiddingAdm = '' //服务端bidding才需要设置
  11944. // private expressLoadAdListener: NativeExpressAdListener = {
  11945. // /**
  11946. // * 加载失败的回调
  11947. // *
  11948. // * @param code
  11949. // * @param message
  11950. // */
  11951. // onError: (code: number, message: string) => {
  11952. // console.error("加载广告失败,code=" + code + ",message=" + message);
  11953. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  11954. // },
  11955. //
  11956. // /**
  11957. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  11958. // *
  11959. // * @param ads 返回的广告列表
  11960. // */
  11961. //
  11962. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  11963. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  11964. // if (ads && ads.length > 0) {
  11965. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  11966. // ad.setExpressInteractionListener({
  11967. // /**
  11968. // *广告的点击回调
  11969. // * @param type 广告的交互类型
  11970. // */
  11971. // onAdClicked: (type: number) => {
  11972. // console.log("BannerExpressAdPage==onAdClicked......");
  11973. // },
  11974. //
  11975. // /**
  11976. // * 广告的展示回调 每个广告仅回调一次
  11977. // * @param type 广告的交互类型
  11978. // */
  11979. // onAdShow: (type: number) => {
  11980. // console.log("BannerExpressAdPage==onAdShow......");
  11981. // },
  11982. //
  11983. // /**
  11984. // * 模板渲染失败
  11985. // */
  11986. // onRenderFail: (code: number, msg: string) => {
  11987. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  11988. // },
  11989. //
  11990. // /**
  11991. // * 模板渲染成功
  11992. // * @param width 返回view的宽 单位 vp
  11993. // * @param height 返回view的高 单位 vp
  11994. // */
  11995. // onRenderSuccess: (width: number, height: number) => {
  11996. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  11997. // this.bannerAd = ad;
  11998. // this.status = "广告加载完成待展示";
  11999. //
  12000. // this.showBannerAd()
  12001. // }
  12002. // })
  12003. // //渲染广告
  12004. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  12005. // this.setDislikeCallback(ad); //设置dislike
  12006. // ad.render(this.getUIContext())
  12007. // this.status = "广告加载中...";
  12008. // });
  12009. // }
  12010. // }
  12011. // }
  12012. //
  12013. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  12014. // ad.setDislikeCallback({
  12015. // /**
  12016. // * dislike show
  12017. // */
  12018. // onShow: () => {
  12019. // console.log("BannerExpressAdPage==dislike......show");
  12020. // },
  12021. //
  12022. // /**
  12023. // * @param position 选择的位置
  12024. // * @param value 选择的内容
  12025. // * @param enforceRemove 是否强制关闭广告
  12026. // */
  12027. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  12028. // this.isShowAd = false;
  12029. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  12030. // ",enforce=" + enforceRemove);
  12031. // },
  12032. //
  12033. // /**
  12034. // * 点击取消
  12035. // */
  12036. // onCancel: () => {
  12037. // console.log("BannerExpressAdPage==dislike......onCancel");
  12038. // }
  12039. //
  12040. // })
  12041. // }
  12042. /**
  12043. * 加载Banner广告
  12044. */
  12045. loadBannerAd(rit: string) {
  12046. // if (Utility.isNoble()) {
  12047. // return
  12048. // }
  12049. // if (!Utility.isPassInstallTime(2)) {
  12050. // return
  12051. // }
  12052. // this.isShowAd = false;
  12053. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  12054. // this.mAdSlot = new AdSlotBuilder()
  12055. // .setCodeId(rit)
  12056. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  12057. // .setAdCount(1)
  12058. // .setBidAdm(this.mBiddingAdm)
  12059. // .build()
  12060. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  12061. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  12062. // this.status = "广告加载中..."
  12063. }
  12064. /**
  12065. * 展示Banner广告
  12066. */
  12067. // showBannerAd() {
  12068. // if (!this.bannerAd) {
  12069. // return
  12070. // }
  12071. // this.isShowAd = true
  12072. // this.status = "已展示"
  12073. // }
  12074. /**
  12075. * 穿山甲广告代码结束
  12076. */
  12077. /**
  12078. * 处理歌单播放请求
  12079. */
  12080. private handlePlaylistPlayRequest(playlistId: string, playlistName: string, songFilePaths: string[], startIndex: number, webDavAuthInfo?: WebDavAuthInfo) {
  12081. try {
  12082. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  12083. // 检查是否为WebDAV播放请求
  12084. if (playlistId === 'webdav-playlist') {
  12085. Logger.info(`heanup 检测到WebDAV播放请求,使用事件传递的认证信息`)
  12086. // 如果有WebDAV认证信息,保存到实例变量和全局上下文中
  12087. if (webDavAuthInfo) {
  12088. this.currentWebDavAuthInfo = webDavAuthInfo;
  12089. // 同时保存到全局上下文作为持久化备份(防止实例变量被清空)
  12090. try {
  12091. const globalContext = GlobalContext.getContext();
  12092. globalContext.setObject('webDavAuthInfo', webDavAuthInfo as Object);
  12093. Logger.info(`heanup 已将WebDAV认证信息保存到实例变量和全局上下文,账户ID: ${webDavAuthInfo.accountId}`);
  12094. } catch (error) {
  12095. Logger.error(`heanup 保存到全局上下文失败:`, error.toString());
  12096. }
  12097. } else {
  12098. Logger.warn(`heanup WebDAV播放请求中没有认证信息`);
  12099. }
  12100. // 尝试从全局上下文获取videoItems(如果WebDavMainPage已经保存了的话)
  12101. const globalContext = GlobalContext.getContext();
  12102. const videoItems = globalContext.getObject('videoItems') as VideoItem[];
  12103. const currentPlayIndex = globalContext.getObject('currentPlayIndex') as number;
  12104. Logger.info(`heanup 从GlobalContext获取数据: videoItems长度=${videoItems?.length || 0}, currentPlayIndex=${currentPlayIndex}`);
  12105. if (videoItems && videoItems.length > 0) {
  12106. Logger.info(`heanup 从全局上下文获取到WebDAV歌曲列表,长度:${videoItems.length}`)
  12107. // 验证歌曲数据是否完整
  12108. for (let i = 0; i < Math.min(3, videoItems.length); i++) {
  12109. Logger.info(`heanup 歌曲[${i}]: ${videoItems[i]?.name}, 路径: ${videoItems[i]?.filePath}`)
  12110. }
  12111. this.finishLoadingPlaylist(videoItems, startIndex, playlistName)
  12112. return
  12113. } else {
  12114. Logger.error(`heanup 无法从全局上下文获取WebDAV歌曲数据,尝试使用传入的文件路径创建备用数据`)
  12115. // 备用方案:直接使用传入的文件路径创建VideoItem
  12116. const fallbackVideoItems: VideoItem[] = [];
  12117. for (let i = 0; i < songFilePaths.length; i++) {
  12118. const fileName = songFilePaths[i].split('/').pop() || `WebDAV歌曲${i+1}`;
  12119. const videoItem = new VideoItem(
  12120. fileName.replace(/\.(flac|mp3|wav|m4a)$/i, ''), // name (去掉扩展名)
  12121. '', // id
  12122. songFilePaths[i], // filePath (URL)
  12123. CommonConstants.TYPE_WEBDAV, // type
  12124. 0, // videoSize
  12125. "0", // cTime
  12126. undefined, // pixelMap
  12127. undefined, // size
  12128. undefined, // pixelMapPath
  12129. "WebDAV", // artist
  12130. undefined, // album
  12131. fileName // fileName
  12132. );
  12133. fallbackVideoItems.push(videoItem);
  12134. }
  12135. Logger.info(`heanup 使用备用方案创建了${fallbackVideoItems.length}首WebDAV歌曲`)
  12136. this.finishLoadingPlaylist(fallbackVideoItems, startIndex, playlistName)
  12137. return
  12138. }
  12139. }
  12140. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  12141. const songMap: Map<number, VideoItem> = new Map()
  12142. let completedQueries = 0
  12143. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  12144. // 遍历所有文件路径,使用索引记录位置
  12145. for (let i = 0; i < songFilePaths.length; i++) {
  12146. const filePath = songFilePaths[i]
  12147. const index = i
  12148. Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  12149. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  12150. const queryPromise = this.table.queryVideoByFilePath(filePath)
  12151. Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  12152. queryPromise.then((videoItem) => {
  12153. completedQueries++
  12154. Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  12155. if (videoItem) {
  12156. // 使用索引作为key保存到Map中,保持原始顺序
  12157. songMap.set(index, videoItem)
  12158. Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  12159. } else {
  12160. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  12161. }
  12162. // 检查是否所有歌曲都已加载完成
  12163. if (completedQueries === songFilePaths.length) {
  12164. Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  12165. // 按照索引顺序重建歌曲数组
  12166. const songs: VideoItem[] = []
  12167. for (let j = 0; j < songFilePaths.length; j++) {
  12168. const song = songMap.get(j)
  12169. if (song) {
  12170. songs.push(song)
  12171. Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  12172. }
  12173. }
  12174. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  12175. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12176. }
  12177. }).catch((error: Error) => {
  12178. completedQueries++
  12179. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  12180. // 即使出错也要检查是否完成所有查询
  12181. if (completedQueries === songFilePaths.length) {
  12182. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  12183. // 按照索引顺序重建歌曲数组
  12184. const songs: VideoItem[] = []
  12185. for (let j = 0; j < songFilePaths.length; j++) {
  12186. const song = songMap.get(j)
  12187. if (song) {
  12188. songs.push(song)
  12189. }
  12190. }
  12191. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12192. }
  12193. })
  12194. }
  12195. } catch (error) {
  12196. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  12197. ToastUtil.showToast('播放失败')
  12198. }
  12199. }
  12200. /**
  12201. * 完成歌单加载并开始播放
  12202. */
  12203. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  12204. if (songs.length === 0) {
  12205. Logger.error('heanup 没有找到任何可播放的歌曲')
  12206. ToastUtil.showToast('没有找到可播放的歌曲')
  12207. return
  12208. }
  12209. this.songList = songs
  12210. this.sonDataSource.pushArrayData(songs)
  12211. this.sonDataSource.notifyDataReload()
  12212. this.curIndex = startIndex
  12213. if (songs[startIndex]) {
  12214. // 确保当前播放的歌曲也更新到存储
  12215. AppStorage.setOrCreate('currentSong', songs[startIndex])
  12216. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  12217. this.doPlay(songs[startIndex], startIndex, true)
  12218. }
  12219. PreferencesUtil.putSync('LastMusicList', this.songList)
  12220. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  12221. }
  12222. }
  12223. //视频气泡窗口的布局
  12224. @Builder
  12225. function customPopupBuilder(dataBu: BubbleBean) {
  12226. List() {
  12227. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  12228. ListItem() {
  12229. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12230. Row() {
  12231. Column() {
  12232. Image(dataBu.imageRes[index])
  12233. .height(28)
  12234. .fillColor(dataBu.color)
  12235. .alignSelf(ItemAlign.Center)
  12236. }
  12237. .width(32)
  12238. Text(item)
  12239. .padding({
  12240. top: 10,
  12241. bottom: 10,
  12242. right: 10,
  12243. left: 10
  12244. })
  12245. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  12246. .textAlign(TextAlign.Start)
  12247. .width("100%")
  12248. }
  12249. }
  12250. .backgroundColor($r('app.color.settings_background_main'))
  12251. .margin({ top: 6, bottom: 6 })
  12252. }
  12253. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12254. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  12255. TransitionEffect.scale({ x: 0, y: 0 })))
  12256. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12257. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12258. .onClick(() => {
  12259. dataBu.onItemClick?.(index)
  12260. })
  12261. })
  12262. }
  12263. .scrollBar(BarState.Off)
  12264. .width(120)
  12265. .divider({
  12266. strokeWidth: 1,
  12267. color: "#22FFFFFF"
  12268. })
  12269. }
  12270. // Function to calculate a hash for the file list
  12271. function simpleHash(fileList: string[]): string {
  12272. let hash = 0;
  12273. const str = fileList.join(',');
  12274. for (let i = 0; i < str.length; i++) {
  12275. const char = str.charCodeAt(i);
  12276. hash = (hash << 5) - hash + char;
  12277. hash |= 0; // Convert to 32bit integer
  12278. }
  12279. return hash.toString();
  12280. }
  12281. interface MoreItem {
  12282. id: number;
  12283. image: Resource;
  12284. title: string;
  12285. }
  12286. //视频气泡窗口的布局
  12287. @Builder
  12288. function cutPopupBuilder(dataBu: BubbleBean) {
  12289. Column() {
  12290. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  12291. .padding({
  12292. top: 10,
  12293. bottom: 10,
  12294. right: 10,
  12295. left: 10
  12296. })
  12297. .textAlign(TextAlign.Start)
  12298. .width(160)
  12299. .fontWeight(666)
  12300. .fontSize(16)
  12301. List() {
  12302. ForEach(dataBu.data, (item: string, index: number) => {
  12303. ListItem() {
  12304. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12305. Row() {
  12306. Column() {
  12307. Image($r('app.media.music_group'))
  12308. .height(28)
  12309. .fillColor(dataBu.color)
  12310. .alignSelf(ItemAlign.Center)
  12311. }
  12312. .width(32)
  12313. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  12314. .padding({
  12315. top: 10,
  12316. bottom: 10,
  12317. right: 10,
  12318. left: 10
  12319. })
  12320. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  12321. .fontSize(15)
  12322. }
  12323. }
  12324. .backgroundColor(Color.Transparent)
  12325. .margin({ top: 7, bottom: 7 })
  12326. }
  12327. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12328. .animation({ duration: 500 }),
  12329. TransitionEffect.scale({ x: 0, y: 0 })))
  12330. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12331. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12332. .onClick(() => {
  12333. dataBu.onItemClick?.(index)
  12334. })
  12335. })
  12336. }
  12337. .scrollBar(BarState.Off)
  12338. .width(150)
  12339. .divider({
  12340. strokeWidth: 1,
  12341. color: "#22FFFFFF"
  12342. })
  12343. }
  12344. .height(300)
  12345. .padding({
  12346. bottom: 30
  12347. })
  12348. }
  12349. function getFileDirName(filePath: string,rootPath:string): string{
  12350. if(filePath===rootPath){
  12351. return '首页'
  12352. }
  12353. let result = FileUtil.getFileName(filePath)
  12354. if(StrUtil.isEmpty(result))
  12355. return ''
  12356. if(result.startsWith('.'))
  12357. result = result.replace(/\./g, '')
  12358. return result
  12359. }
  12360. //只扫描当前目录下文件(不扫描子文件夹)的方法
  12361. @Concurrent
  12362. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  12363. const table: MediaTable = new MediaTable(context);
  12364. try {
  12365. // 直接获取当前目录下的文件列表
  12366. const files = FileUtil.listFileSync(dirPath);
  12367. await Promise.all(files.map(async (file) => {
  12368. const fPath = `${dirPath}/${file}`;
  12369. // 跳过目录,只处理文件
  12370. if (FileUtil.isDirectory(fPath)) {
  12371. return;
  12372. }
  12373. // 跳过特定格式文件
  12374. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  12375. return;
  12376. }
  12377. // 检查是否为媒体文件
  12378. if (Utility.isMeidaByExtension(fPath)) {
  12379. let mType = CommonConstants.TYPE_LOCAL;
  12380. if (fPath.includes(lockPath)) {
  12381. mType = CommonConstants.TYPE_LOCK;
  12382. }
  12383. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  12384. context, fPath, mType, true
  12385. );
  12386. table.insert(mediaItem, (id: number) => {
  12387. // 插入回调函数
  12388. }, cover_api);
  12389. }
  12390. }));
  12391. } catch (error) {
  12392. console.error(' 扫描当前目录失败:', error);
  12393. }
  12394. }